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.
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.
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.
24 /* All the functions starting with "x" call bb_error_msg_and_die() if they
25 * fail, so callers never need to check for errors. If it returned, it
28 void FAST_FUNC
bb_die_memory_exhausted(void)
30 bb_simple_error_msg_and_die(bb_msg_memory_exhausted
);
34 /* dmalloc provides variants of these that do abort() on failure.
35 * Since dmalloc's prototypes overwrite the impls here as they are
36 * included after these prototypes in libbb.h, all is well.
38 // Warn if we can't allocate size bytes of memory.
39 void* FAST_FUNC
malloc_or_warn(size_t size
)
41 void *ptr
= malloc(size
);
42 if (ptr
== NULL
&& size
!= 0)
43 bb_simple_error_msg(bb_msg_memory_exhausted
);
47 // Die if we can't allocate size bytes of memory.
48 void* FAST_FUNC
xmalloc(size_t size
)
50 void *ptr
= malloc(size
);
51 if (ptr
== NULL
&& size
!= 0)
52 bb_die_memory_exhausted();
56 // Die if we can't resize previously allocated memory. (This returns a pointer
57 // to the new memory, which may or may not be the same as the old memory.
58 // It'll copy the contents to a new chunk and free the old one if necessary.)
59 void* FAST_FUNC
xrealloc(void *ptr
, size_t size
)
61 ptr
= realloc(ptr
, size
);
62 if (ptr
== NULL
&& size
!= 0)
63 bb_die_memory_exhausted();
68 // Die if we can't allocate and zero size bytes of memory.
69 void* FAST_FUNC
xzalloc(size_t size
)
71 void *ptr
= xmalloc(size
);
76 // Die if we can't copy a string to freshly allocated memory.
77 char* FAST_FUNC
xstrdup(const char *s
)
87 bb_die_memory_exhausted();
92 // Die if we can't allocate n+1 bytes (space for the null terminator) and copy
93 // the (possibly truncated to length n) string into it.
94 char* FAST_FUNC
xstrndup(const char *s
, size_t n
)
101 bb_die_memory_exhausted();
106 void* FAST_FUNC
xmemdup(const void *s
, size_t n
)
108 return memcpy(xmalloc(n
), s
, n
);
111 void* FAST_FUNC
mmap_read(int fd
, size_t size
)
113 return mmap(NULL
, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
116 void* FAST_FUNC
mmap_anon(size_t size
)
118 return mmap(NULL
, size
,
119 PROT_READ
| PROT_WRITE
,
120 MAP_PRIVATE
| MAP_ANONYMOUS
,
121 /* ignored: */ -1, 0);
124 void* FAST_FUNC
xmmap_anon(size_t size
)
126 void *p
= mmap_anon(size
);
128 bb_die_memory_exhausted();
132 // Die if we can't open a file and return a FILE* to it.
133 // Notice we haven't got xfread(), This is for use with fscanf() and friends.
134 FILE* FAST_FUNC
xfopen(const char *path
, const char *mode
)
136 FILE *fp
= fopen(path
, mode
);
138 bb_perror_msg_and_die("can't open '%s'", path
);
142 // Die if we can't open a file and return a fd.
143 int FAST_FUNC
xopen3(const char *pathname
, int flags
, int mode
)
147 ret
= open(pathname
, flags
, mode
);
149 bb_perror_msg_and_die("can't open '%s'", pathname
);
154 // Die if we can't open a file and return a fd.
155 int FAST_FUNC
xopen(const char *pathname
, int flags
)
157 return xopen3(pathname
, flags
, 0666);
160 // Warn if we can't open a file and return a fd.
161 int FAST_FUNC
open3_or_warn(const char *pathname
, int flags
, int mode
)
165 ret
= open(pathname
, flags
, mode
);
167 bb_perror_msg("can't open '%s'", pathname
);
172 // Warn if we can't open a file and return a fd.
173 int FAST_FUNC
open_or_warn(const char *pathname
, int flags
)
175 return open3_or_warn(pathname
, flags
, 0666);
178 /* Die if we can't open an existing file readonly with O_NONBLOCK
180 * Note that for ioctl O_RDONLY is sufficient.
182 int FAST_FUNC
xopen_nonblocking(const char *pathname
)
184 return xopen(pathname
, O_RDONLY
| O_NONBLOCK
);
187 int FAST_FUNC
xopen_as_uid_gid(const char *pathname
, int flags
, uid_t u
, gid_t g
)
190 uid_t old_euid
= geteuid();
191 gid_t old_egid
= getegid();
196 fd
= xopen(pathname
, flags
);
204 void FAST_FUNC
xunlink(const char *pathname
)
206 if (unlink(pathname
))
207 bb_perror_msg_and_die("can't remove file '%s'", pathname
);
210 void FAST_FUNC
xrename(const char *oldpath
, const char *newpath
)
212 if (rename(oldpath
, newpath
))
213 bb_perror_msg_and_die("can't move '%s' to '%s'", oldpath
, newpath
);
216 int FAST_FUNC
rename_or_warn(const char *oldpath
, const char *newpath
)
218 int n
= rename(oldpath
, newpath
);
220 bb_perror_msg("can't move '%s' to '%s'", oldpath
, newpath
);
224 void FAST_FUNC
xpipe(int *filedes
)
227 bb_simple_perror_msg_and_die("can't create pipe");
230 void FAST_FUNC
xdup2(int from
, int to
)
232 if (dup2(from
, to
) != to
)
233 bb_simple_perror_msg_and_die("can't duplicate file descriptor");
234 // " %d to %d", from, to);
237 // "Renumber" opened fd
238 void FAST_FUNC
xmove_fd(int from
, int to
)
246 // Die with an error message if we can't write the entire buffer.
247 void FAST_FUNC
xwrite(int fd
, const void *buf
, size_t count
)
250 ssize_t size
= full_write(fd
, buf
, count
);
251 if ((size_t)size
!= count
) {
253 * Two cases: write error immediately;
254 * or some writes succeeded, then we hit an error.
255 * In either case, errno is set.
257 bb_simple_perror_msg_and_die(
258 size
>= 0 ? "short write" : "write error"
263 void FAST_FUNC
xwrite_str(int fd
, const char *str
)
265 xwrite(fd
, str
, strlen(str
));
268 void FAST_FUNC
xclose(int fd
)
271 bb_simple_perror_msg_and_die("close failed");
274 // Die with an error message if we can't lseek to the right spot.
275 off_t FAST_FUNC
xlseek(int fd
, off_t offset
, int whence
)
277 off_t off
= lseek(fd
, offset
, whence
);
278 if (off
== (off_t
)-1) {
279 bb_perror_msg_and_die("lseek(%"OFF_FMT
"u, %d)", offset
, whence
);
284 int FAST_FUNC
xmkstemp(char *template)
286 int fd
= mkstemp(template);
288 bb_perror_msg_and_die("can't create temp file '%s'", template);
292 // Die with supplied filename if this FILE* has ferror set.
293 void FAST_FUNC
die_if_ferror(FILE *fp
, const char *fn
)
296 /* ferror doesn't set useful errno */
297 bb_error_msg_and_die("%s: I/O error", fn
);
301 // Die with an error message if stdout has ferror set.
302 void FAST_FUNC
die_if_ferror_stdout(void)
304 die_if_ferror(stdout
, bb_msg_standard_output
);
307 int FAST_FUNC
fflush_all(void)
313 int FAST_FUNC
bb_putchar(int ch
)
318 int FAST_FUNC
fputs_stdout(const char *s
)
320 return fputs(s
, stdout
);
323 /* Die with an error message if we can't copy an entire FILE* to stdout,
324 * then close that file. */
325 void FAST_FUNC
xprint_and_close_file(FILE *file
)
328 // copyfd outputs error messages for us.
329 if (bb_copyfd_eof(fileno(file
), STDOUT_FILENO
) == -1)
335 // Die with an error message if we can't malloc() enough space and do an
336 // sprintf() into that space.
337 char* FAST_FUNC
xasprintf(const char *format
, ...)
344 r
= vasprintf(&string_ptr
, format
, p
);
348 bb_die_memory_exhausted();
352 void FAST_FUNC
xsetenv(const char *key
, const char *value
)
354 if (setenv(key
, value
, 1))
355 bb_die_memory_exhausted();
358 /* Handles "VAR=VAL" strings, even those which are part of environ
361 void FAST_FUNC
bb_unsetenv(const char *var
)
363 char onstack
[128 - 16]; /* smaller stack setup code on x86 */
366 tp
= strchr(var
, '=');
368 /* In case var was putenv'ed, we can't replace '='
369 * with NUL and unsetenv(var) - it won't work,
370 * env is modified by the replacement, unsetenv
371 * sees "VAR" instead of "VAR=VAL" and does not remove it!
374 unsigned sz
= tp
- var
;
375 if (sz
< sizeof(onstack
)) {
376 ((char*)mempcpy(onstack
, var
, sz
))[0] = '\0';
380 /* unlikely: very long var name */
381 var
= tp
= xstrndup(var
, sz
);
388 void FAST_FUNC
bb_unsetenv_and_free(char *var
)
394 // Die with an error message if we can't set gid. (Because resource limits may
395 // limit this user to a given number of processes, and if that fills up the
396 // setgid() will fail and we'll _still_be_root_, which is bad.)
397 void FAST_FUNC
xsetgid(gid_t gid
)
399 if (setgid(gid
)) bb_simple_perror_msg_and_die("setgid");
402 // Die with an error message if we can't set uid. (See xsetgid() for why.)
403 void FAST_FUNC
xsetuid(uid_t uid
)
405 if (setuid(uid
)) bb_simple_perror_msg_and_die("setuid");
408 void FAST_FUNC
xsetegid(gid_t egid
)
410 if (setegid(egid
)) bb_simple_perror_msg_and_die("setegid");
413 void FAST_FUNC
xseteuid(uid_t euid
)
415 if (seteuid(euid
)) bb_simple_perror_msg_and_die("seteuid");
418 int FAST_FUNC
chdir_or_warn(const char *path
)
422 bb_perror_msg("can't change directory to '%s'", path
);
425 // Die if we can't chdir to a new path.
426 void FAST_FUNC
xchdir(const char *path
)
428 if (chdir_or_warn(path
) != 0)
432 void FAST_FUNC
xfchdir(int fd
)
435 bb_simple_perror_msg_and_die("fchdir");
438 void FAST_FUNC
xchroot(const char *path
)
441 bb_perror_msg_and_die("can't change root directory to '%s'", path
);
445 // Print a warning message if opendir() fails, but don't die.
446 DIR* FAST_FUNC
warn_opendir(const char *path
)
452 bb_perror_msg("can't open '%s'", path
);
456 // Die with an error message if opendir() fails.
457 DIR* FAST_FUNC
xopendir(const char *path
)
463 bb_perror_msg_and_die("can't open '%s'", path
);
467 // Die with an error message if we can't open a new socket.
468 int FAST_FUNC
xsocket(int domain
, int type
, int protocol
)
470 int r
= socket(domain
, type
, protocol
);
473 /* Hijack vaguely related config option */
474 #if ENABLE_VERBOSE_RESOLUTION_ERRORS
475 const char *s
= "INET";
477 if (domain
== AF_PACKET
) s
= "PACKET";
480 if (domain
== AF_NETLINK
) s
= "NETLINK";
482 IF_FEATURE_IPV6(if (domain
== AF_INET6
) s
= "INET6";)
483 bb_perror_msg_and_die("socket(AF_%s,%d,%d)", s
, type
, protocol
);
485 bb_simple_perror_msg_and_die("socket");
492 // Die with an error message if we can't bind a socket to an address.
493 void FAST_FUNC
xbind(int sockfd
, struct sockaddr
*my_addr
, socklen_t addrlen
)
495 if (bind(sockfd
, my_addr
, addrlen
)) bb_simple_perror_msg_and_die("bind");
498 // Die with an error message if we can't listen for connections on a socket.
499 void FAST_FUNC
xlisten(int s
, int backlog
)
501 if (listen(s
, backlog
)) bb_simple_perror_msg_and_die("listen");
504 /* Die with an error message if sendto failed.
505 * Return bytes sent otherwise */
506 ssize_t FAST_FUNC
xsendto(int s
, const void *buf
, size_t len
, const struct sockaddr
*to
,
509 ssize_t ret
= sendto(s
, buf
, len
, 0, to
, tolen
);
511 if (ENABLE_FEATURE_CLEAN_UP
)
513 bb_simple_perror_msg_and_die("sendto");
518 // xstat() - a stat() which dies on failure with meaningful error message
519 void FAST_FUNC
xstat(const char *name
, struct stat
*stat_buf
)
521 if (stat(name
, stat_buf
))
522 bb_perror_msg_and_die("can't stat '%s'", name
);
525 void FAST_FUNC
xfstat(int fd
, struct stat
*stat_buf
, const char *errmsg
)
527 /* errmsg is usually a file name, but not always:
528 * xfstat may be called in a spot where file name is no longer
529 * available, and caller may give e.g. "can't stat input file" string.
531 if (fstat(fd
, stat_buf
))
532 bb_simple_perror_msg_and_die(errmsg
);
536 // selinux_or_die() - die if SELinux is disabled.
537 void FAST_FUNC
selinux_or_die(void)
539 int rc
= is_selinux_enabled();
541 bb_simple_error_msg_and_die("SELinux is disabled");
543 bb_simple_error_msg_and_die("is_selinux_enabled() failed");
547 /* not defined, other code must have no calls to it */
550 int FAST_FUNC
ioctl_or_perror_and_die(int fd
, unsigned request
, void *argp
, const char *fmt
,...)
555 ret
= ioctl(fd
, request
, argp
);
558 bb_verror_msg(fmt
, p
, strerror(errno
));
559 /* xfunc_die can actually longjmp, so be nice */
566 int FAST_FUNC
ioctl_or_perror(int fd
, unsigned request
, void *argp
, const char *fmt
,...)
569 int ret
= ioctl(fd
, request
, argp
);
573 bb_verror_msg(fmt
, p
, strerror(errno
));
579 #if ENABLE_IOCTL_HEX2STR_ERROR
580 int FAST_FUNC
bb_ioctl_or_warn(int fd
, unsigned request
, void *argp
, const char *ioctl_name
)
584 ret
= ioctl(fd
, request
, argp
);
586 bb_simple_perror_msg(ioctl_name
);
589 int FAST_FUNC
bb_xioctl(int fd
, unsigned request
, void *argp
, const char *ioctl_name
)
593 ret
= ioctl(fd
, request
, argp
);
595 bb_simple_perror_msg_and_die(ioctl_name
);
599 int FAST_FUNC
bb_ioctl_or_warn(int fd
, unsigned request
, void *argp
)
603 ret
= ioctl(fd
, request
, argp
);
605 bb_perror_msg("ioctl %#x failed", request
);
608 int FAST_FUNC
bb_xioctl(int fd
, unsigned request
, void *argp
)
612 ret
= ioctl(fd
, request
, argp
);
614 bb_perror_msg_and_die("ioctl %#x failed", request
);
619 char* FAST_FUNC
xmalloc_ttyname(int fd
)
622 int r
= ttyname_r(fd
, buf
, sizeof(buf
) - 1);
628 void FAST_FUNC
generate_uuid(uint8_t *buf
)
630 /* http://www.ietf.org/rfc/rfc4122.txt
631 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
632 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
634 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
635 * | time_mid | time_hi_and_version |
636 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
637 * |clk_seq_and_variant | node (0-1) |
638 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
640 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
641 * IOW, uuid has this layout:
642 * uint32_t time_low (big endian)
643 * uint16_t time_mid (big endian)
644 * uint16_t time_hi_and_version (big endian)
645 * version is a 4-bit field:
647 * 2 DCE Security, with embedded POSIX UIDs
649 * 4 Randomly generated
650 * 5 Name-based (SHA-1)
651 * uint16_t clk_seq_and_variant (big endian)
652 * variant is a 3-bit field:
653 * 0xx Reserved, NCS backward compatibility
654 * 10x The variant specified in rfc4122
655 * 110 Reserved, Microsoft backward compatibility
656 * 111 Reserved for future definition
659 * For version 4, these bits are set/cleared:
660 * time_hi_and_version & 0x0fff | 0x4000
661 * clk_seq_and_variant & 0x3fff | 0x8000
666 open_read_close("/dev/urandom", buf
, 16);
667 /* Paranoia. /dev/urandom may be missing.
668 * rand() is guaranteed to generate at least [0, 2^15) range,
669 * but lowest bits in some libc are not so "random".
671 srand(monotonic_us()); /* pulls in printf */
674 for (i
= 0; i
< 16; i
++)
675 buf
[i
] ^= rand() >> 5;
683 buf
[4 + 2 ] = (buf
[4 + 2 ] & 0x0f) | 0x40;
685 buf
[4 + 2 + 2] = (buf
[4 + 2 + 2] & 0x3f) | 0x80;
689 pid_t FAST_FUNC
xfork(void)
693 if (pid
< 0) /* wtf? */
694 bb_simple_perror_msg_and_die("vfork"+1);
699 void FAST_FUNC
xvfork_parent_waits_and_exits(void)
707 int exit_status
= wait_for_exitstatus(pid
);
708 if (WIFSIGNALED(exit_status
))
709 kill_myself_with_sig(WTERMSIG(exit_status
));
710 _exit(WEXITSTATUS(exit_status
));
712 /* Child continues */
715 // Useful when we do know that pid is valid, and we just want to wait
716 // for it to exit. Not existing pid is fatal. waitpid() status is not returned.
717 int FAST_FUNC
wait_for_exitstatus(pid_t pid
)
721 n
= safe_waitpid(pid
, &exit_status
, 0);
723 bb_simple_perror_msg_and_die("waitpid");
727 void FAST_FUNC
xsettimeofday(const struct timeval
*tv
)
729 if (settimeofday(tv
, NULL
))
730 bb_simple_perror_msg_and_die("settimeofday");
733 void FAST_FUNC
xgettimeofday(struct timeval
*tv
)
736 if (gettimeofday(tv
, NULL
))
737 bb_simple_perror_msg_and_die("gettimeofday");
739 /* Never fails on Linux */
740 gettimeofday(tv
, NULL
);