xfuncs.c 6.9 KB

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