xfuncs.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. char* FAST_FUNC utoa_to_buf(unsigned n, char *buf, unsigned buflen)
  57. {
  58. unsigned i, out, res;
  59. if (buflen) {
  60. out = 0;
  61. BUILD_BUG_ON(sizeof(n) != 4 && sizeof(n) != 8);
  62. if (sizeof(n) == 4)
  63. // 2^32-1 = 4294967295
  64. i = 1000000000;
  65. #if UINT_MAX > 0xffffffff /* prevents warning about "const too large" */
  66. else
  67. if (sizeof(n) == 8)
  68. // 2^64-1 = 18446744073709551615
  69. i = 10000000000000000000;
  70. #endif
  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. /* Envvars override even if "value" from ioctl is valid (>0).
  205. * Rationale: it's impossible to guess what user wants.
  206. * For example: "man CMD | ...": should "man" format output
  207. * to stdout's width? stdin's width? /dev/tty's width? 80 chars?
  208. * We _cant_ know it. If "..." saves text for e.g. email,
  209. * then it's probably 80 chars.
  210. * If "..." is, say, "grep -v DISCARD | $PAGER", then user
  211. * would prefer his tty's width to be used!
  212. *
  213. * Since we don't know, at least allow user to do this:
  214. * "COLUMNS=80 man CMD | ..."
  215. */
  216. char *s = getenv(env_name);
  217. if (s) {
  218. value = atoi(s);
  219. /* If LINES/COLUMNS are set, pretend that there is
  220. * no error getting w/h, this prevents some ugly
  221. * cursor tricks by our callers */
  222. *err = 0;
  223. }
  224. if (value <= 1 || value >= 30000)
  225. value = def_val;
  226. return value;
  227. }
  228. /* It is perfectly ok to pass in a NULL for either width or for
  229. * height, in which case that value will not be set. */
  230. int FAST_FUNC get_terminal_width_height(int fd, unsigned *width, unsigned *height)
  231. {
  232. struct winsize win;
  233. int err;
  234. int close_me = -1;
  235. if (fd == -1) {
  236. if (isatty(STDOUT_FILENO))
  237. fd = STDOUT_FILENO;
  238. else
  239. if (isatty(STDERR_FILENO))
  240. fd = STDERR_FILENO;
  241. else
  242. if (isatty(STDIN_FILENO))
  243. fd = STDIN_FILENO;
  244. else
  245. close_me = fd = open("/dev/tty", O_RDONLY);
  246. }
  247. win.ws_row = 0;
  248. win.ws_col = 0;
  249. /* I've seen ioctl returning 0, but row/col is (still?) 0.
  250. * We treat that as an error too. */
  251. err = ioctl(fd, TIOCGWINSZ, &win) != 0 || win.ws_row == 0;
  252. if (height)
  253. *height = wh_helper(win.ws_row, 24, "LINES", &err);
  254. if (width)
  255. *width = wh_helper(win.ws_col, 80, "COLUMNS", &err);
  256. if (close_me >= 0)
  257. close(close_me);
  258. return err;
  259. }
  260. int FAST_FUNC get_terminal_width(int fd)
  261. {
  262. unsigned width;
  263. get_terminal_width_height(fd, &width, NULL);
  264. return width;
  265. }
  266. int FAST_FUNC is_TERM_dumb(void)
  267. {
  268. char *term = getenv("TERM");
  269. return term && strcmp(term, "dumb") == 0;
  270. }
  271. int FAST_FUNC tcsetattr_stdin_TCSANOW(const struct termios *tp)
  272. {
  273. return tcsetattr(STDIN_FILENO, TCSANOW, tp);
  274. }
  275. int FAST_FUNC get_termios_and_make_raw(int fd, struct termios *newterm, struct termios *oldterm, int flags)
  276. {
  277. //TODO: slattach, shell read might be adapted to use this too: grep for "tcsetattr", "[VTIME] = 0"
  278. int r;
  279. memset(oldterm, 0, sizeof(*oldterm)); /* paranoia */
  280. r = tcgetattr(fd, oldterm);
  281. *newterm = *oldterm;
  282. /* Turn off buffered input (ICANON)
  283. * Turn off echoing (ECHO)
  284. * and separate echoing of newline (ECHONL, normally off anyway)
  285. */
  286. newterm->c_lflag &= ~(ICANON | ECHO | ECHONL);
  287. if (flags & TERMIOS_CLEAR_ISIG) {
  288. /* dont recognize INT/QUIT/SUSP chars */
  289. newterm->c_lflag &= ~ISIG;
  290. }
  291. /* reads will block only if < 1 char is available */
  292. newterm->c_cc[VMIN] = 1;
  293. /* no timeout (reads block forever) */
  294. newterm->c_cc[VTIME] = 0;
  295. /* IXON, IXOFF, and IXANY:
  296. * IXOFF=1: sw flow control is enabled on input queue:
  297. * tty transmits a STOP char when input queue is close to full
  298. * and transmits a START char when input queue is nearly empty.
  299. * IXON=1: sw flow control is enabled on output queue:
  300. * tty will stop sending if STOP char is received,
  301. * and resume sending if START is received, or if any char
  302. * is received and IXANY=1.
  303. */
  304. if (flags & TERMIOS_RAW_CRNL_INPUT) {
  305. /* IXON=0: XON/XOFF chars are treated as normal chars (why we do this?) */
  306. /* dont convert CR to NL on input */
  307. newterm->c_iflag &= ~(IXON | ICRNL);
  308. }
  309. if (flags & TERMIOS_RAW_CRNL_OUTPUT) {
  310. /* dont convert NL to CR+NL on output */
  311. newterm->c_oflag &= ~(ONLCR);
  312. /* Maybe clear more c_oflag bits? Usually, only OPOST and ONLCR are set.
  313. * OPOST Enable output processing (reqd for OLCUC and *NL* bits to work)
  314. * OLCUC Map lowercase characters to uppercase on output.
  315. * OCRNL Map CR to NL on output.
  316. * ONOCR Don't output CR at column 0.
  317. * ONLRET Don't output CR.
  318. */
  319. }
  320. if (flags & TERMIOS_RAW_INPUT) {
  321. #ifndef IMAXBEL
  322. # define IMAXBEL 0
  323. #endif
  324. #ifndef IUCLC
  325. # define IUCLC 0
  326. #endif
  327. #ifndef IXANY
  328. # define IXANY 0
  329. #endif
  330. /* IXOFF=0: disable sending XON/XOFF if input buf is full
  331. * IXON=0: input XON/XOFF chars are not special
  332. * BRKINT=0: dont send SIGINT on break
  333. * IMAXBEL=0: dont echo BEL on input line too long
  334. * INLCR,ICRNL,IUCLC: dont convert anything on input
  335. */
  336. newterm->c_iflag &= ~(IXOFF|IXON|IXANY|BRKINT|INLCR|ICRNL|IUCLC|IMAXBEL);
  337. }
  338. return r;
  339. }
  340. int FAST_FUNC set_termios_to_raw(int fd, struct termios *oldterm, int flags)
  341. {
  342. struct termios newterm;
  343. get_termios_and_make_raw(fd, &newterm, oldterm, flags);
  344. return tcsetattr(fd, TCSANOW, &newterm);
  345. }
  346. pid_t FAST_FUNC safe_waitpid(pid_t pid, int *wstat, int options)
  347. {
  348. pid_t r;
  349. do
  350. r = waitpid(pid, wstat, options);
  351. while ((r == -1) && (errno == EINTR));
  352. return r;
  353. }
  354. pid_t FAST_FUNC wait_any_nohang(int *wstat)
  355. {
  356. return safe_waitpid(-1, wstat, WNOHANG);
  357. }
  358. // Wait for the specified child PID to exit, returning child's error return.
  359. int FAST_FUNC wait4pid(pid_t pid)
  360. {
  361. int status;
  362. if (pid <= 0) {
  363. /*errno = ECHILD; -- wrong. */
  364. /* we expect errno to be already set from failed [v]fork/exec */
  365. return -1;
  366. }
  367. if (safe_waitpid(pid, &status, 0) == -1)
  368. return -1;
  369. if (WIFEXITED(status))
  370. return WEXITSTATUS(status);
  371. if (WIFSIGNALED(status))
  372. return WTERMSIG(status) + 0x180;
  373. return 0;
  374. }