xfuncs.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. /* Envvars override even if "value" from ioctl is valid (>0).
  207. * Rationale: it's impossible to guess what user wants.
  208. * For example: "man CMD | ...": should "man" format output
  209. * to stdout's width? stdin's width? /dev/tty's width? 80 chars?
  210. * We _cant_ know it. If "..." saves text for e.g. email,
  211. * then it's probably 80 chars.
  212. * If "..." is, say, "grep -v DISCARD | $PAGER", then user
  213. * would prefer his tty's width to be used!
  214. *
  215. * Since we don't know, at least allow user to do this:
  216. * "COLUMNS=80 man CMD | ..."
  217. */
  218. char *s = getenv(env_name);
  219. if (s) {
  220. value = atoi(s);
  221. /* If LINES/COLUMNS are set, pretend that there is
  222. * no error getting w/h, this prevents some ugly
  223. * cursor tricks by our callers */
  224. *err = 0;
  225. }
  226. if (value <= 1 || value >= 30000)
  227. value = def_val;
  228. return value;
  229. }
  230. /* It is perfectly ok to pass in a NULL for either width or for
  231. * height, in which case that value will not be set. */
  232. int FAST_FUNC get_terminal_width_height(int fd, unsigned *width, unsigned *height)
  233. {
  234. struct winsize win;
  235. int err;
  236. int close_me = -1;
  237. if (fd == -1) {
  238. if (isatty(STDOUT_FILENO))
  239. fd = STDOUT_FILENO;
  240. else
  241. if (isatty(STDERR_FILENO))
  242. fd = STDERR_FILENO;
  243. else
  244. if (isatty(STDIN_FILENO))
  245. fd = STDIN_FILENO;
  246. else
  247. close_me = fd = open("/dev/tty", O_RDONLY);
  248. }
  249. win.ws_row = 0;
  250. win.ws_col = 0;
  251. /* I've seen ioctl returning 0, but row/col is (still?) 0.
  252. * We treat that as an error too. */
  253. err = ioctl(fd, TIOCGWINSZ, &win) != 0 || win.ws_row == 0;
  254. if (height)
  255. *height = wh_helper(win.ws_row, 24, "LINES", &err);
  256. if (width)
  257. *width = wh_helper(win.ws_col, 80, "COLUMNS", &err);
  258. if (close_me >= 0)
  259. close(close_me);
  260. return err;
  261. }
  262. int FAST_FUNC get_terminal_width(int fd)
  263. {
  264. unsigned width;
  265. get_terminal_width_height(fd, &width, NULL);
  266. return width;
  267. }
  268. int FAST_FUNC tcsetattr_stdin_TCSANOW(const struct termios *tp)
  269. {
  270. return tcsetattr(STDIN_FILENO, TCSANOW, tp);
  271. }
  272. int FAST_FUNC set_termios_to_raw(int fd, struct termios *oldterm, int flags)
  273. {
  274. //TODO: lineedit, microcom and less might be adapted to use this too:
  275. // grep for "tcsetattr"
  276. struct termios newterm;
  277. tcgetattr(fd, oldterm);
  278. newterm = *oldterm;
  279. /* Turn off buffered input (ICANON)
  280. * Turn off echoing (ECHO)
  281. * and separate echoing of newline (ECHONL, normally off anyway)
  282. */
  283. newterm.c_lflag &= ~(ICANON | ECHO | ECHONL);
  284. if (flags & TERMIOS_CLEAR_ISIG) {
  285. /* dont recognize INT/QUIT/SUSP chars */
  286. newterm.c_lflag &= ~ISIG;
  287. }
  288. /* reads will block only if < 1 char is available */
  289. newterm.c_cc[VMIN] = 1;
  290. /* no timeout (reads block forever) */
  291. newterm.c_cc[VTIME] = 0;
  292. if (flags & TERMIOS_RAW_CRNL) {
  293. /* dont convert CR to NL on input */
  294. newterm.c_iflag &= ~(IXON | ICRNL);
  295. /* dont convert NL to CR on output */
  296. newterm.c_oflag &= ~(ONLCR);
  297. }
  298. if (flags & TERMIOS_RAW_INPUT) {
  299. /* dont convert anything on input */
  300. newterm.c_iflag &= ~(BRKINT|INLCR|ICRNL|IXON|IXOFF|IUCLC|IXANY|IMAXBEL);
  301. }
  302. return tcsetattr(fd, TCSANOW, &newterm);
  303. }
  304. pid_t FAST_FUNC safe_waitpid(pid_t pid, int *wstat, int options)
  305. {
  306. pid_t r;
  307. do
  308. r = waitpid(pid, wstat, options);
  309. while ((r == -1) && (errno == EINTR));
  310. return r;
  311. }
  312. pid_t FAST_FUNC wait_any_nohang(int *wstat)
  313. {
  314. return safe_waitpid(-1, wstat, WNOHANG);
  315. }
  316. // Wait for the specified child PID to exit, returning child's error return.
  317. int FAST_FUNC wait4pid(pid_t pid)
  318. {
  319. int status;
  320. if (pid <= 0) {
  321. /*errno = ECHILD; -- wrong. */
  322. /* we expect errno to be already set from failed [v]fork/exec */
  323. return -1;
  324. }
  325. if (safe_waitpid(pid, &status, 0) == -1)
  326. return -1;
  327. if (WIFEXITED(status))
  328. return WEXITSTATUS(status);
  329. if (WIFSIGNALED(status))
  330. return WTERMSIG(status) + 0x180;
  331. return 0;
  332. }
  333. // Useful when we do know that pid is valid, and we just want to wait
  334. // for it to exit. Not existing pid is fatal. waitpid() status is not returned.
  335. int FAST_FUNC wait_for_exitstatus(pid_t pid)
  336. {
  337. int exit_status, n;
  338. n = safe_waitpid(pid, &exit_status, 0);
  339. if (n < 0)
  340. bb_perror_msg_and_die("waitpid");
  341. return exit_status;
  342. }