common.h 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. /*
  2. * Copyright (c) Artem Bityutskiy, 2007, 2008
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
  12. * the GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17. */
  18. #ifndef __MTD_UTILS_COMMON_H__
  19. #define __MTD_UTILS_COMMON_H__
  20. #include <stdbool.h>
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <ctype.h>
  24. #include <string.h>
  25. #include <fcntl.h>
  26. #include <errno.h>
  27. #include <features.h>
  28. #include <inttypes.h>
  29. #include <unistd.h>
  30. #include <sys/sysmacros.h>
  31. #include "config.h"
  32. #ifndef PROGRAM_NAME
  33. # error "You must define PROGRAM_NAME before including this header"
  34. #endif
  35. #ifdef __cplusplus
  36. extern "C" {
  37. #endif
  38. #ifndef MIN /* some C lib headers define this for us */
  39. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  40. #endif
  41. #ifndef MAX
  42. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  43. #endif
  44. #define min(a, b) MIN(a, b) /* glue for linux kernel source */
  45. #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
  46. #define ALIGN(x,a) __ALIGN_MASK(x,(typeof(x))(a)-1)
  47. #define __ALIGN_MASK(x,mask) (((x)+(mask))&~(mask))
  48. #define min_t(t,x,y) ({ \
  49. typeof((x)) _x = (x); \
  50. typeof((y)) _y = (y); \
  51. (_x < _y) ? _x : _y; \
  52. })
  53. #define max_t(t,x,y) ({ \
  54. typeof((x)) _x = (x); \
  55. typeof((y)) _y = (y); \
  56. (_x > _y) ? _x : _y; \
  57. })
  58. /*
  59. * This looks more complex than it should be. But we need to
  60. * get the type for the ~ right in round_down (it needs to be
  61. * as wide as the result!), and we want to evaluate the macro
  62. * arguments just once each.
  63. */
  64. #define __round_mask(x, y) ((__typeof__(x))((y)-1))
  65. #define round_up(x, y) ((((x)-1) | __round_mask(x, y))+1)
  66. #define round_down(x, y) ((x) & ~__round_mask(x, y))
  67. #ifndef O_CLOEXEC
  68. #define O_CLOEXEC 0
  69. #endif
  70. /* Verbose messages */
  71. #define bareverbose(verbose, fmt, ...) do { \
  72. if (verbose) \
  73. printf(fmt, ##__VA_ARGS__); \
  74. } while(0)
  75. #define verbose(verbose, fmt, ...) \
  76. bareverbose(verbose, "%s: " fmt "\n", PROGRAM_NAME, ##__VA_ARGS__)
  77. /* Normal messages */
  78. #define normsg_cont(fmt, ...) do { \
  79. printf("%s: " fmt, PROGRAM_NAME, ##__VA_ARGS__); \
  80. } while(0)
  81. #define normsg(fmt, ...) do { \
  82. normsg_cont(fmt "\n", ##__VA_ARGS__); \
  83. } while(0)
  84. /* Error messages */
  85. #define errmsg(fmt, ...) ({ \
  86. fprintf(stderr, "%s: error!: " fmt "\n", PROGRAM_NAME, ##__VA_ARGS__); \
  87. -1; \
  88. })
  89. #define errmsg_die(fmt, ...) do { \
  90. exit(errmsg(fmt, ##__VA_ARGS__)); \
  91. } while(0)
  92. /* System error messages */
  93. #define sys_errmsg(fmt, ...) ({ \
  94. int _err = errno; \
  95. errmsg(fmt, ##__VA_ARGS__); \
  96. fprintf(stderr, "%*serror %d (%s)\n", (int)sizeof(PROGRAM_NAME) + 1,\
  97. "", _err, strerror(_err)); \
  98. -1; \
  99. })
  100. #define sys_errmsg_die(fmt, ...) do { \
  101. exit(sys_errmsg(fmt, ##__VA_ARGS__)); \
  102. } while(0)
  103. /* Warnings */
  104. #define warnmsg(fmt, ...) do { \
  105. fprintf(stderr, "%s: warning!: " fmt "\n", PROGRAM_NAME, ##__VA_ARGS__); \
  106. } while(0)
  107. /* for tagging functions that always exit */
  108. #if defined(__GNUC__) || defined(__clang__)
  109. #define NORETURN __attribute__((noreturn))
  110. #else
  111. #define NORETURN
  112. #endif
  113. /**
  114. * prompt the user for confirmation
  115. */
  116. static inline bool prompt(const char *msg, bool def)
  117. {
  118. bool ret = def;
  119. char line[64];
  120. do {
  121. normsg_cont("%s (%c/%c) ", msg, def ? 'Y' : 'y', def ? 'n' : 'N');
  122. fflush(stdout);
  123. if (fgets(line, sizeof(line), stdin) == NULL) {
  124. printf("failed to read prompt; assuming '%s'\n",
  125. def ? "yes" : "no");
  126. break;
  127. }
  128. if (strcmp("\n", line) != 0) {
  129. switch (line[0]) {
  130. case 'N':
  131. case 'n': ret = false; break;
  132. case 'Y':
  133. case 'y': ret = true; break;
  134. default:
  135. puts("unknown response; please try again");
  136. continue;
  137. }
  138. }
  139. break;
  140. } while (1);
  141. return ret;
  142. }
  143. static inline int is_power_of_2(unsigned long long n)
  144. {
  145. return (n != 0 && ((n & (n - 1)) == 0));
  146. }
  147. /* Check whether buffer is filled with character 'pattern' */
  148. static inline int buffer_check_pattern(unsigned char *buffer, size_t size,
  149. unsigned char pattern)
  150. {
  151. /* Invalid input */
  152. if (!buffer || (size == 0))
  153. return 0;
  154. /* No match on first byte */
  155. if (*buffer != pattern)
  156. return 0;
  157. /* First byte matched and buffer is 1 byte long, OK. */
  158. if (size == 1)
  159. return 1;
  160. /*
  161. * Check buffer longer than 1 byte. We already know that buffer[0]
  162. * matches the pattern, so the test below only checks whether the
  163. * buffer[0...size-2] == buffer[1...size-1] , which is a test for
  164. * whether the buffer is filled with constant value.
  165. */
  166. return !memcmp(buffer, buffer + 1, size - 1);
  167. }
  168. /**
  169. * simple_strtoX - convert a hex/dec/oct string into a number
  170. * @snum: buffer to convert
  171. * @error: set to 1 when buffer isn't fully consumed
  172. *
  173. * These functions are similar to the standard strtoX() functions, but they are
  174. * a little bit easier to use if you want to convert full string of digits into
  175. * the binary form. The typical usage:
  176. *
  177. * int error = 0;
  178. * unsigned long num;
  179. *
  180. * num = simple_strtoul(str, &error);
  181. * if (error || ... if needed, your check that num is not out of range ...)
  182. * error_happened();
  183. */
  184. #define simple_strtoX(func, type) \
  185. static inline type simple_##func(const char *snum, int *error) \
  186. { \
  187. char *endptr; \
  188. type ret = func(snum, &endptr, 0); \
  189. \
  190. if (error && (!*snum || *endptr)) { \
  191. errmsg("%s: unable to parse the number '%s'", #func, snum); \
  192. *error = 1; \
  193. } \
  194. \
  195. return ret; \
  196. }
  197. simple_strtoX(strtol, long int)
  198. simple_strtoX(strtoll, long long int)
  199. simple_strtoX(strtoul, unsigned long int)
  200. simple_strtoX(strtoull, unsigned long long int)
  201. /* Simple version-printing for utils */
  202. #define common_print_version() \
  203. do { \
  204. printf("%s (mtd-utils) %s\n", PROGRAM_NAME, VERSION); \
  205. } while (0)
  206. #include "xalloc.h"
  207. long long util_get_bytes(const char *str);
  208. void util_print_bytes(long long bytes, int bracket);
  209. int util_srand(void);
  210. /*
  211. * The following helpers are here to avoid compiler complaints about unchecked
  212. * return code.
  213. * FIXME: The proper fix would be to check the return code in all those places,
  214. * but it's usually placed in old code which have no proper exit path and
  215. * handling errors requires rewriting a lot of code.
  216. *
  217. * WARNING: Please do not use these helpers in new code. Instead, make sure
  218. * you check the function return code and provide coherent error handling in
  219. * case of error.
  220. */
  221. static inline ssize_t read_nocheck(int fd, void *buf, size_t count)
  222. {
  223. return read(fd, buf, count);
  224. }
  225. static inline ssize_t write_nocheck(int fd, void *buf, size_t count)
  226. {
  227. return write(fd, buf, count);
  228. }
  229. static inline ssize_t pread_nocheck(int fd, void *buf, size_t count,
  230. off_t offset)
  231. {
  232. return pread(fd, buf, count, offset);
  233. }
  234. static inline ssize_t pwrite_nocheck(int fd, void *buf, size_t count,
  235. off_t offset)
  236. {
  237. return pwrite(fd, buf, count, offset);
  238. }
  239. #ifdef __cplusplus
  240. }
  241. #endif
  242. #endif /* !__MTD_UTILS_COMMON_H__ */