1 /* vi: set sw=4 ts=4: */
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6 * Copyright (C) 2006 Rob Landley
7 * Copyright (C) 2006 Denys Vlasenko
9 * Licensed under GPLv2, see file LICENSE in this source tree.
12 /* We need to have separate xfuncs.c and xfuncs_printf.c because
13 * with current linkers, even with section garbage collection,
14 * if *.o module references any of XXXprintf functions, you pull in
15 * entire printf machinery. Even if you do not use the function
16 * which uses XXXprintf.
18 * xfuncs.c contains functions (not necessarily xfuncs)
19 * which do not pull in printf, directly or indirectly.
20 * xfunc_printf.c contains those which do.
22 * TODO: move xmalloc() and xatonum() here.
27 /* Turn on nonblocking I/O on a fd */
28 int FAST_FUNC ndelay_on(int fd)
30 int flags = fcntl(fd, F_GETFL);
31 if (flags & O_NONBLOCK)
33 fcntl(fd, F_SETFL, flags | O_NONBLOCK);
37 int FAST_FUNC ndelay_off(int fd)
39 int flags = fcntl(fd, F_GETFL);
40 if (!(flags & O_NONBLOCK))
42 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
46 void FAST_FUNC close_on_exec_on(int fd)
48 fcntl(fd, F_SETFD, FD_CLOEXEC);
51 char* FAST_FUNC strncpy_IFNAMSIZ(char *dst, const char *src)
54 enum { IFNAMSIZ = 16 };
56 return strncpy(dst, src, IFNAMSIZ);
60 /* Convert unsigned integer to ascii, writing into supplied buffer.
61 * A truncated result contains the first few digits of the result ala strncpy.
62 * Returns a pointer past last generated digit, does _not_ store NUL.
64 void BUG_sizeof(void);
65 char* FAST_FUNC utoa_to_buf(unsigned n, char *buf, unsigned buflen)
72 // 2^32-1 = 4294967295
74 #if UINT_MAX > 4294967295 /* prevents warning about "const too large" */
77 // 2^64-1 = 18446744073709551615
78 i = 10000000000000000000;
85 if (res || out || i == 1) {
96 /* Convert signed integer to ascii, like utoa_to_buf() */
97 char* FAST_FUNC itoa_to_buf(int n, char *buf, unsigned buflen)
106 return utoa_to_buf((unsigned)n, buf, buflen);
109 // The following two functions use a static buffer, so calling either one a
110 // second time will overwrite previous results.
112 // The largest 32 bit integer is -2 billion plus NUL, or 1+10+1=12 bytes.
113 // It so happens that sizeof(int) * 3 is enough for 32+ bit ints.
114 // (sizeof(int) * 3 + 2 is correct for any width, even 8-bit)
116 static char local_buf[sizeof(int) * 3];
118 /* Convert unsigned integer to ascii using a static buffer (returned). */
119 char* FAST_FUNC utoa(unsigned n)
121 *(utoa_to_buf(n, local_buf, sizeof(local_buf) - 1)) = '\0';
126 /* Convert signed integer to ascii using a static buffer (returned). */
127 char* FAST_FUNC itoa(int n)
129 *(itoa_to_buf(n, local_buf, sizeof(local_buf) - 1)) = '\0';
134 /* Emit a string of hex representation of bytes */
135 char* FAST_FUNC bin2hex(char *p, const char *cp, int count)
138 unsigned char c = *cp++;
139 /* put lowercase hex digits */
140 *p++ = 0x20 | bb_hexdigits_upcase[c >> 4];
141 *p++ = 0x20 | bb_hexdigits_upcase[c & 0xf];
147 /* Convert "[x]x[:][x]x[:][x]x[:][x]x" hex string to binary, no more than COUNT bytes */
148 char* FAST_FUNC hex2bin(char *dst, const char *str, int count)
151 while (*str && count) {
156 else if ((c|0x20) >= 'a' && (c|0x20) <= 'f')
157 val = (c|0x20) - ('a' - 10);
164 else if ((c|0x20) >= 'a' && (c|0x20) <= 'f')
165 val |= (c|0x20) - ('a' - 10);
166 else if (c == ':' || c == '\0')
178 errno = (*str ? ERANGE : 0);
182 /* Return how long the file at fd is, if there's any way to determine it. */
184 off_t FAST_FUNC fdlength(int fd)
186 off_t bottom = 0, top = 0, pos;
189 // If the ioctl works for this, return it.
191 if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512;
193 // FIXME: explain why lseek(SEEK_END) is not used here!
195 // If not, do a binary search for the last location we can read. (Some
196 // block devices don't do BLKGETSIZE right.)
201 pos = bottom + (top - bottom) / 2;
203 // If we can read from the current location, it's bigger.
205 if (lseek(fd, pos, SEEK_SET)>=0 && safe_read(fd, &temp, 1)==1) {
206 if (bottom == top) bottom = top = (top+1) * 2;
209 // If we can't, it's smaller.
217 } while (bottom + 1 != top);
223 int FAST_FUNC bb_putchar_stderr(char ch)
225 return write(STDERR_FILENO, &ch, 1);
228 ssize_t FAST_FUNC full_write1_str(const char *str)
230 return full_write(STDOUT_FILENO, str, strlen(str));
233 ssize_t FAST_FUNC full_write2_str(const char *str)
235 return full_write(STDERR_FILENO, str, strlen(str));
238 static int wh_helper(int value, int def_val, const char *env_name, int *err)
240 /* Envvars override even if "value" from ioctl is valid (>0).
241 * Rationale: it's impossible to guess what user wants.
242 * For example: "man CMD | ...": should "man" format output
243 * to stdout's width? stdin's width? /dev/tty's width? 80 chars?
244 * We _cant_ know it. If "..." saves text for e.g. email,
245 * then it's probably 80 chars.
246 * If "..." is, say, "grep -v DISCARD | $PAGER", then user
247 * would prefer his tty's width to be used!
249 * Since we don't know, at least allow user to do this:
250 * "COLUMNS=80 man CMD | ..."
252 char *s = getenv(env_name);
255 /* If LINES/COLUMNS are set, pretend that there is
256 * no error getting w/h, this prevents some ugly
257 * cursor tricks by our callers */
261 if (value <= 1 || value >= 30000)
266 /* It is perfectly ok to pass in a NULL for either width or for
267 * height, in which case that value will not be set. */
268 int FAST_FUNC get_terminal_width_height(int fd, unsigned *width, unsigned *height)
275 if (isatty(STDOUT_FILENO))
278 if (isatty(STDERR_FILENO))
281 if (isatty(STDIN_FILENO))
284 close_me = fd = open("/dev/tty", O_RDONLY);
289 /* I've seen ioctl returning 0, but row/col is (still?) 0.
290 * We treat that as an error too. */
291 err = ioctl(fd, TIOCGWINSZ, &win) != 0 || win.ws_row == 0;
293 *height = wh_helper(win.ws_row, 24, "LINES", &err);
295 *width = wh_helper(win.ws_col, 80, "COLUMNS", &err);
302 int FAST_FUNC get_terminal_width(int fd)
305 get_terminal_width_height(fd, &width, NULL);
309 int FAST_FUNC tcsetattr_stdin_TCSANOW(const struct termios *tp)
311 return tcsetattr(STDIN_FILENO, TCSANOW, tp);
314 int FAST_FUNC get_termios_and_make_raw(int fd, struct termios *newterm, struct termios *oldterm, int flags)
316 //TODO: slattach, shell read might be adapted to use this too: grep for "tcsetattr", "[VTIME] = 0"
319 memset(oldterm, 0, sizeof(*oldterm)); /* paranoia */
320 r = tcgetattr(fd, oldterm);
323 /* Turn off buffered input (ICANON)
324 * Turn off echoing (ECHO)
325 * and separate echoing of newline (ECHONL, normally off anyway)
327 newterm->c_lflag &= ~(ICANON | ECHO | ECHONL);
328 if (flags & TERMIOS_CLEAR_ISIG) {
329 /* dont recognize INT/QUIT/SUSP chars */
330 newterm->c_lflag &= ~ISIG;
332 /* reads will block only if < 1 char is available */
333 newterm->c_cc[VMIN] = 1;
334 /* no timeout (reads block forever) */
335 newterm->c_cc[VTIME] = 0;
336 if (flags & TERMIOS_RAW_CRNL) {
337 /* IXON, IXOFF, and IXANY:
338 * IXOFF=1: sw flow control is enabled on input queue:
339 * tty transmits a STOP char when input queue is close to full
340 * and transmits a START char when input queue is nearly empty.
341 * IXON=1: sw flow control is enabled on output queue:
342 * tty will stop sending if STOP char is received,
343 * and resume sending if START is received, or if any char
344 * is received and IXANY=1.
346 /* IXON=0: XON/XOFF chars are treated as normal chars (why we do this?) */
347 /* dont convert CR to NL on input */
348 newterm->c_iflag &= ~(IXON | ICRNL);
349 /* dont convert NL to CR+NL on output */
350 newterm->c_oflag &= ~(ONLCR);
351 /* Maybe clear more c_oflag bits? Usually, only OPOST and ONLCR are set.
352 * OPOST Enable output processing (reqd for OLCUC and *NL* bits to work)
353 * OLCUC Map lowercase characters to uppercase on output.
354 * OCRNL Map CR to NL on output.
355 * ONOCR Don't output CR at column 0.
356 * ONLRET Don't output CR.
359 if (flags & TERMIOS_RAW_INPUT) {
360 /* IXOFF=0: disable sending XON/XOFF if input buf is full */
361 /* IXON=0: input XON/XOFF chars are not special */
362 /* dont convert anything on input */
363 newterm->c_iflag &= ~(IXOFF|IXON|IXANY|BRKINT|INLCR|ICRNL|IUCLC|IMAXBEL);
368 int FAST_FUNC set_termios_to_raw(int fd, struct termios *oldterm, int flags)
370 struct termios newterm;
372 get_termios_and_make_raw(fd, &newterm, oldterm, flags);
373 return tcsetattr(fd, TCSANOW, &newterm);
376 pid_t FAST_FUNC safe_waitpid(pid_t pid, int *wstat, int options)
381 r = waitpid(pid, wstat, options);
382 while ((r == -1) && (errno == EINTR));
386 pid_t FAST_FUNC wait_any_nohang(int *wstat)
388 return safe_waitpid(-1, wstat, WNOHANG);
391 // Wait for the specified child PID to exit, returning child's error return.
392 int FAST_FUNC wait4pid(pid_t pid)
397 /*errno = ECHILD; -- wrong. */
398 /* we expect errno to be already set from failed [v]fork/exec */
401 if (safe_waitpid(pid, &status, 0) == -1)
403 if (WIFEXITED(status))
404 return WEXITSTATUS(status);
405 if (WIFSIGNALED(status))
406 return WTERMSIG(status) + 0x180;
410 // Useful when we do know that pid is valid, and we just want to wait
411 // for it to exit. Not existing pid is fatal. waitpid() status is not returned.
412 int FAST_FUNC wait_for_exitstatus(pid_t pid)
416 n = safe_waitpid(pid, &exit_status, 0);
418 bb_perror_msg_and_die("waitpid");