xfuncs.c 7.5 KB

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