xfuncs.c 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. * Copyright (C) 2006 Rob Landley
  7. * Copyright (C) 2006 Denys Vlasenko
  8. *
  9. * Licensed under GPLv2, see file LICENSE in this source tree.
  10. */
  11. /* We need to have separate xfuncs.c and xfuncs_printf.c because
  12. * with current linkers, even with section garbage collection,
  13. * if *.o module references any of XXXprintf functions, you pull in
  14. * entire printf machinery. Even if you do not use the function
  15. * which uses XXXprintf.
  16. *
  17. * xfuncs.c contains functions (not necessarily xfuncs)
  18. * which do not pull in printf, directly or indirectly.
  19. * xfunc_printf.c contains those which do.
  20. *
  21. * TODO: move xmalloc() and xatonum() here.
  22. */
  23. #include "libbb.h"
  24. /* Turn on nonblocking I/O on a fd */
  25. void FAST_FUNC ndelay_on(int fd)
  26. {
  27. int flags = fcntl(fd, F_GETFL);
  28. if (flags & O_NONBLOCK)
  29. return;
  30. fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  31. }
  32. void FAST_FUNC ndelay_off(int fd)
  33. {
  34. int flags = fcntl(fd, F_GETFL);
  35. if (!(flags & O_NONBLOCK))
  36. return;
  37. fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
  38. }
  39. void FAST_FUNC close_on_exec_on(int fd)
  40. {
  41. fcntl(fd, F_SETFD, FD_CLOEXEC);
  42. }
  43. char* FAST_FUNC strncpy_IFNAMSIZ(char *dst, const char *src)
  44. {
  45. #ifndef IFNAMSIZ
  46. enum { IFNAMSIZ = 16 };
  47. #endif
  48. return strncpy(dst, src, IFNAMSIZ);
  49. }
  50. /* Convert unsigned integer to ascii, writing into supplied buffer.
  51. * A truncated result contains the first few digits of the result ala strncpy.
  52. * Returns a pointer past last generated digit, does _not_ store NUL.
  53. */
  54. void BUG_sizeof(void);
  55. char* FAST_FUNC utoa_to_buf(unsigned n, char *buf, unsigned buflen)
  56. {
  57. unsigned i, out, res;
  58. if (buflen) {
  59. out = 0;
  60. if (sizeof(n) == 4)
  61. // 2^32-1 = 4294967295
  62. i = 1000000000;
  63. #if UINT_MAX > 4294967295 /* prevents warning about "const too large" */
  64. else
  65. if (sizeof(n) == 8)
  66. // 2^64-1 = 18446744073709551615
  67. i = 10000000000000000000;
  68. #endif
  69. else
  70. BUG_sizeof();
  71. for (; i; i /= 10) {
  72. res = n / i;
  73. n = n % i;
  74. if (res || out || i == 1) {
  75. if (--buflen == 0)
  76. break;
  77. out++;
  78. *buf++ = '0' + res;
  79. }
  80. }
  81. }
  82. return buf;
  83. }
  84. /* Convert signed integer to ascii, like utoa_to_buf() */
  85. char* FAST_FUNC itoa_to_buf(int n, char *buf, unsigned buflen)
  86. {
  87. if (!buflen)
  88. return buf;
  89. if (n < 0) {
  90. n = -n;
  91. *buf++ = '-';
  92. buflen--;
  93. }
  94. return utoa_to_buf((unsigned)n, buf, buflen);
  95. }
  96. // The following two functions use a static buffer, so calling either one a
  97. // second time will overwrite previous results.
  98. //
  99. // The largest 32 bit integer is -2 billion plus NUL, or 1+10+1=12 bytes.
  100. // It so happens that sizeof(int) * 3 is enough for 32+ bit ints.
  101. // (sizeof(int) * 3 + 2 is correct for any width, even 8-bit)
  102. static char local_buf[sizeof(int) * 3];
  103. /* Convert unsigned integer to ascii using a static buffer (returned). */
  104. char* FAST_FUNC utoa(unsigned n)
  105. {
  106. *(utoa_to_buf(n, local_buf, sizeof(local_buf) - 1)) = '\0';
  107. return local_buf;
  108. }
  109. /* Convert signed integer to ascii using a static buffer (returned). */
  110. char* FAST_FUNC itoa(int n)
  111. {
  112. *(itoa_to_buf(n, local_buf, sizeof(local_buf) - 1)) = '\0';
  113. return local_buf;
  114. }
  115. /* Emit a string of hex representation of bytes */
  116. char* FAST_FUNC bin2hex(char *p, const char *cp, int count)
  117. {
  118. while (count) {
  119. unsigned char c = *cp++;
  120. /* put lowercase hex digits */
  121. *p++ = 0x20 | bb_hexdigits_upcase[c >> 4];
  122. *p++ = 0x20 | bb_hexdigits_upcase[c & 0xf];
  123. count--;
  124. }
  125. return p;
  126. }
  127. /* Convert "[x]x[:][x]x[:][x]x[:][x]x" hex string to binary, no more than COUNT bytes */
  128. char* FAST_FUNC hex2bin(char *dst, const char *str, int count)
  129. {
  130. errno = EINVAL;
  131. while (*str && count) {
  132. uint8_t val;
  133. uint8_t c = *str++;
  134. if (isdigit(c))
  135. val = c - '0';
  136. else if ((c|0x20) >= 'a' && (c|0x20) <= 'f')
  137. val = (c|0x20) - ('a' - 10);
  138. else
  139. return NULL;
  140. val <<= 4;
  141. c = *str;
  142. if (isdigit(c))
  143. val |= c - '0';
  144. else if ((c|0x20) >= 'a' && (c|0x20) <= 'f')
  145. val |= (c|0x20) - ('a' - 10);
  146. else if (c == ':' || c == '\0')
  147. val >>= 4;
  148. else
  149. return NULL;
  150. *dst++ = val;
  151. if (c != '\0')
  152. str++;
  153. if (*str == ':')
  154. str++;
  155. count--;
  156. }
  157. errno = (*str ? ERANGE : 0);
  158. return dst;
  159. }
  160. /* Return how long the file at fd is, if there's any way to determine it. */
  161. #ifdef UNUSED
  162. off_t FAST_FUNC fdlength(int fd)
  163. {
  164. off_t bottom = 0, top = 0, pos;
  165. long size;
  166. // If the ioctl works for this, return it.
  167. if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512;
  168. // FIXME: explain why lseek(SEEK_END) is not used here!
  169. // If not, do a binary search for the last location we can read. (Some
  170. // block devices don't do BLKGETSIZE right.)
  171. do {
  172. char temp;
  173. pos = bottom + (top - bottom) / 2;
  174. // If we can read from the current location, it's bigger.
  175. if (lseek(fd, pos, SEEK_SET)>=0 && safe_read(fd, &temp, 1)==1) {
  176. if (bottom == top) bottom = top = (top+1) * 2;
  177. else bottom = pos;
  178. // If we can't, it's smaller.
  179. } else {
  180. if (bottom == top) {
  181. if (!top) return 0;
  182. bottom = top/2;
  183. }
  184. else top = pos;
  185. }
  186. } while (bottom + 1 != top);
  187. return pos + 1;
  188. }
  189. #endif
  190. int FAST_FUNC bb_putchar_stderr(char ch)
  191. {
  192. return write(STDERR_FILENO, &ch, 1);
  193. }
  194. ssize_t FAST_FUNC full_write1_str(const char *str)
  195. {
  196. return full_write(STDOUT_FILENO, str, strlen(str));
  197. }
  198. ssize_t FAST_FUNC full_write2_str(const char *str)
  199. {
  200. return full_write(STDERR_FILENO, str, strlen(str));
  201. }
  202. static int wh_helper(int value, int def_val, const char *env_name, int *err)
  203. {
  204. if (value == 0) {
  205. char *s = getenv(env_name);
  206. if (s) {
  207. value = atoi(s);
  208. /* If LINES/COLUMNS are set, pretend that there is
  209. * no error getting w/h, this prevents some ugly
  210. * cursor tricks by our callers */
  211. *err = 0;
  212. }
  213. }
  214. if (value <= 1 || value >= 30000)
  215. value = def_val;
  216. return value;
  217. }
  218. /* It is perfectly ok to pass in a NULL for either width or for
  219. * height, in which case that value will not be set. */
  220. int FAST_FUNC get_terminal_width_height(int fd, unsigned *width, unsigned *height)
  221. {
  222. struct winsize win;
  223. int err;
  224. win.ws_row = 0;
  225. win.ws_col = 0;
  226. /* I've seen ioctl returning 0, but row/col is (still?) 0.
  227. * We treat that as an error too. */
  228. err = ioctl(fd, TIOCGWINSZ, &win) != 0 || win.ws_row == 0;
  229. if (height)
  230. *height = wh_helper(win.ws_row, 24, "LINES", &err);
  231. if (width)
  232. *width = wh_helper(win.ws_col, 80, "COLUMNS", &err);
  233. return err;
  234. }
  235. int FAST_FUNC tcsetattr_stdin_TCSANOW(const struct termios *tp)
  236. {
  237. return tcsetattr(STDIN_FILENO, TCSANOW, tp);
  238. }
  239. pid_t FAST_FUNC safe_waitpid(pid_t pid, int *wstat, int options)
  240. {
  241. pid_t r;
  242. do
  243. r = waitpid(pid, wstat, options);
  244. while ((r == -1) && (errno == EINTR));
  245. return r;
  246. }
  247. pid_t FAST_FUNC wait_any_nohang(int *wstat)
  248. {
  249. return safe_waitpid(-1, wstat, WNOHANG);
  250. }
  251. // Wait for the specified child PID to exit, returning child's error return.
  252. int FAST_FUNC wait4pid(pid_t pid)
  253. {
  254. int status;
  255. if (pid <= 0) {
  256. /*errno = ECHILD; -- wrong. */
  257. /* we expect errno to be already set from failed [v]fork/exec */
  258. return -1;
  259. }
  260. if (safe_waitpid(pid, &status, 0) == -1)
  261. return -1;
  262. if (WIFEXITED(status))
  263. return WEXITSTATUS(status);
  264. if (WIFSIGNALED(status))
  265. return WTERMSIG(status) + 0x180;
  266. return 0;
  267. }