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 Denis Vlasenko
9 * Licensed under GPL version 2, see file LICENSE in this tarball for details.
14 /* All the functions starting with "x" call bb_error_msg_and_die() if they
15 * fail, so callers never need to check for errors. If it returned, it
19 /* dmalloc provides variants of these that do abort() on failure.
20 * Since dmalloc's prototypes overwrite the impls here as they are
21 * included after these prototypes in libbb.h, all is well.
23 // Warn if we can't allocate size bytes of memory.
24 void *malloc_or_warn(size_t size)
26 void *ptr = malloc(size);
27 if (ptr == NULL && size != 0)
28 bb_error_msg(bb_msg_memory_exhausted);
32 // Die if we can't allocate size bytes of memory.
33 void *xmalloc(size_t size)
35 void *ptr = malloc(size);
36 if (ptr == NULL && size != 0)
37 bb_error_msg_and_die(bb_msg_memory_exhausted);
41 // Die if we can't resize previously allocated memory. (This returns a pointer
42 // to the new memory, which may or may not be the same as the old memory.
43 // It'll copy the contents to a new chunk and free the old one if necessary.)
44 void *xrealloc(void *ptr, size_t size)
46 ptr = realloc(ptr, size);
47 if (ptr == NULL && size != 0)
48 bb_error_msg_and_die(bb_msg_memory_exhausted);
53 // Die if we can't allocate and zero size bytes of memory.
54 void *xzalloc(size_t size)
56 void *ptr = xmalloc(size);
61 // Die if we can't copy a string to freshly allocated memory.
62 char * xstrdup(const char *s)
72 bb_error_msg_and_die(bb_msg_memory_exhausted);
77 // Die if we can't allocate n+1 bytes (space for the null terminator) and copy
78 // the (possibly truncated to length n) string into it.
79 char * xstrndup(const char *s, int n)
84 if (ENABLE_DEBUG && s == NULL)
85 bb_error_msg_and_die("xstrndup bug");
87 /* We can just xmalloc(n+1) and strncpy into it, */
88 /* but think about xstrndup("abc", 10000) wastage! */
100 return memcpy(t, s, n);
103 // Die if we can't open a file and return a FILE * to it.
104 // Notice we haven't got xfread(), This is for use with fscanf() and friends.
105 FILE *xfopen(const char *path, const char *mode)
107 FILE *fp = fopen(path, mode);
109 bb_perror_msg_and_die("%s", path);
113 // Die if we can't open an existing file and return an fd.
114 int xopen(const char *pathname, int flags)
116 //if (ENABLE_DEBUG && (flags & O_CREAT))
117 // bb_error_msg_and_die("xopen() with O_CREAT");
119 return xopen3(pathname, flags, 0666);
122 // Die if we can't open a new file and return an fd.
123 int xopen3(const char *pathname, int flags, int mode)
127 ret = open(pathname, flags, mode);
129 bb_perror_msg_and_die("%s", pathname);
134 void xunlink(const char *pathname)
136 if (unlink(pathname))
137 bb_perror_msg_and_die("cannot remove file '%s'", pathname);
140 // Turn on nonblocking I/O on a fd
141 int ndelay_on(int fd)
143 return fcntl(fd,F_SETFL,fcntl(fd,F_GETFL,0) | O_NONBLOCK);
146 int ndelay_off(int fd)
148 return fcntl(fd,F_SETFL,fcntl(fd,F_GETFL,0) & ~O_NONBLOCK);
151 // "Renumber" opened fd
152 void xmove_fd(int from, int to)
156 if (dup2(from, to) != to)
157 bb_perror_msg_and_die("cannot duplicate file descriptor");
161 // Die with an error message if we can't write the entire buffer.
162 void xwrite(int fd, const void *buf, size_t count)
165 ssize_t size = full_write(fd, buf, count);
167 bb_error_msg_and_die("short write");
171 // Die with an error message if we can't lseek to the right spot.
172 off_t xlseek(int fd, off_t offset, int whence)
174 off_t off = lseek(fd, offset, whence);
175 if (off == (off_t)-1) {
176 if (whence == SEEK_SET)
177 bb_perror_msg_and_die("lseek(%"OFF_FMT"u)", offset);
178 bb_perror_msg_and_die("lseek");
183 // Die with supplied filename if this FILE * has ferror set.
184 void die_if_ferror(FILE *fp, const char *fn)
187 bb_error_msg_and_die("%s: I/O error", fn);
191 // Die with an error message if stdout has ferror set.
192 void die_if_ferror_stdout(void)
194 die_if_ferror(stdout, bb_msg_standard_output);
197 // Die with an error message if we have trouble flushing stdout.
198 void xfflush_stdout(void)
200 if (fflush(stdout)) {
201 bb_perror_msg_and_die(bb_msg_standard_output);
205 void sig_block(int sig)
210 sigprocmask(SIG_BLOCK, &ss, NULL);
213 void sig_unblock(int sig)
218 sigprocmask(SIG_UNBLOCK, &ss, NULL);
222 void sig_blocknone(void)
226 sigprocmask(SIG_SETMASK, &ss, NULL);
230 void sig_catch(int sig, void (*f)(int))
235 sigemptyset(&sa.sa_mask);
236 sigaction(sig, &sa, NULL);
247 void xsetenv(const char *key, const char *value)
249 if (setenv(key, value, 1))
250 bb_error_msg_and_die(bb_msg_memory_exhausted);
253 // Converts unsigned long long value into compact 4-char
254 // representation. Examples: "1234", "1.2k", " 27M", "123T"
255 // Fifth char is always '\0'
256 void smart_ulltoa5(unsigned long long ul, char buf[5])
262 if (ul > 9999*10) { // do not scale if 9999 or less
263 while (ul >= 10000) {
268 v = ul; // ullong divisions are expensive, avoid them
271 if (!idx) { // 9999 or less: use 1234 format
272 c = buf[0] = " 123456789"[v/10000];
273 if (c != ' ') fmt = "0123456789";
274 c = buf[1] = fmt[v/1000%10];
275 if (c != ' ') fmt = "0123456789";
276 buf[2] = fmt[v/100%10];
277 buf[3] = "0123456789"[v/10%10];
279 if (v >= 10*10) { // scaled value is >=10: use 123M format
280 c = buf[0] = " 123456789"[v/1000];
281 if (c != ' ') fmt = "0123456789";
282 buf[1] = fmt[v/100%10];
283 buf[2] = "0123456789"[v/10%10];
284 } else { // scaled value is <10: use 1.2M format
285 buf[0] = "0123456789"[v/10];
287 buf[2] = "0123456789"[v%10];
289 // see http://en.wikipedia.org/wiki/Tera
290 buf[3] = " kMGTPEZY"[idx];
295 // Convert unsigned integer to ascii, writing into supplied buffer.
296 // A truncated result contains the first few digits of the result ala strncpy.
297 // Returns a pointer past last generated digit, does _not_ store NUL.
298 void BUG_sizeof_unsigned_not_4(void);
299 char *utoa_to_buf(unsigned n, char *buf, unsigned buflen)
301 unsigned i, out, res;
302 if (sizeof(unsigned) != 4)
303 BUG_sizeof_unsigned_not_4();
306 for (i = 1000000000; i; i /= 10) {
308 if (res || out || i == 1) {
309 if (!--buflen) break;
319 // Convert signed integer to ascii, like utoa_to_buf()
320 char *itoa_to_buf(int n, char *buf, unsigned buflen)
327 return utoa_to_buf((unsigned)n, buf, buflen);
330 // The following two functions use a static buffer, so calling either one a
331 // second time will overwrite previous results.
333 // The largest 32 bit integer is -2 billion plus null terminator, or 12 bytes.
334 // Int should always be 32 bits on any remotely Unix-like system, see
335 // http://www.unix.org/whitepapers/64bit.html for the reasons why.
337 static char local_buf[12];
339 // Convert unsigned integer to ascii using a static buffer (returned).
340 char *utoa(unsigned n)
342 *(utoa_to_buf(n, local_buf, sizeof(local_buf))) = '\0';
347 // Convert signed integer to ascii using a static buffer (returned).
350 *(itoa_to_buf(n, local_buf, sizeof(local_buf))) = '\0';
355 // Emit a string of hex representation of bytes
356 char *bin2hex(char *p, const char *cp, int count)
359 unsigned char c = *cp++;
360 /* put lowercase hex digits */
361 *p++ = 0x20 | bb_hexdigits_upcase[c >> 4];
362 *p++ = 0x20 | bb_hexdigits_upcase[c & 0xf];
368 // Die with an error message if we can't set gid. (Because resource limits may
369 // limit this user to a given number of processes, and if that fills up the
370 // setgid() will fail and we'll _still_be_root_, which is bad.)
371 void xsetgid(gid_t gid)
373 if (setgid(gid)) bb_error_msg_and_die("setgid");
376 // Die with an error message if we can't set uid. (See xsetgid() for why.)
377 void xsetuid(uid_t uid)
379 if (setuid(uid)) bb_error_msg_and_die("setuid");
382 // Return how long the file at fd is, if there's any way to determine it.
383 off_t fdlength(int fd)
385 off_t bottom = 0, top = 0, pos;
388 // If the ioctl works for this, return it.
390 if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512;
392 // FIXME: explain why lseek(SEEK_END) is not used here!
394 // If not, do a binary search for the last location we can read. (Some
395 // block devices don't do BLKGETSIZE right.)
400 pos = bottom + (top - bottom) / 2;
402 // If we can read from the current location, it's bigger.
404 if (lseek(fd, pos, SEEK_SET)>=0 && safe_read(fd, &temp, 1)==1) {
405 if (bottom == top) bottom = top = (top+1) * 2;
408 // If we can't, it's smaller.
417 } while (bottom + 1 != top);
422 // Die with an error message if we can't malloc() enough space and do an
423 // sprintf() into that space.
424 char *xasprintf(const char *format, ...)
433 r = vasprintf(&string_ptr, format, p);
436 // Bloat for systems that haven't got the GNU extension.
438 r = vsnprintf(NULL, 0, format, p);
440 string_ptr = xmalloc(r+1);
442 r = vsnprintf(string_ptr, r+1, format, p);
446 if (r < 0) bb_error_msg_and_die(bb_msg_memory_exhausted);
450 #if 0 /* If we will ever meet a libc which hasn't [f]dprintf... */
451 int fdprintf(int fd, const char *format, ...)
460 r = vasprintf(&string_ptr, format, p);
463 // Bloat for systems that haven't got the GNU extension.
465 r = vsnprintf(NULL, 0, format, p);
467 string_ptr = xmalloc(r+1);
469 r = vsnprintf(string_ptr, r+1, format, p);
474 full_write(fd, string_ptr, r);
481 // Die with an error message if we can't copy an entire FILE * to stdout, then
483 void xprint_and_close_file(FILE *file)
486 // copyfd outputs error messages for us.
487 if (bb_copyfd_eof(fileno(file), 1) == -1)
493 // Die if we can't chdir to a new path.
494 void xchdir(const char *path)
497 bb_perror_msg_and_die("chdir(%s)", path);
500 // Print a warning message if opendir() fails, but don't die.
501 DIR *warn_opendir(const char *path)
507 bb_perror_msg("cannot open '%s'", path);
511 // Die with an error message if opendir() fails.
512 DIR *xopendir(const char *path)
518 bb_perror_msg_and_die("cannot open '%s'", path);
522 // Die with an error message if we can't open a new socket.
523 int xsocket(int domain, int type, int protocol)
525 int r = socket(domain, type, protocol);
527 if (r < 0) bb_perror_msg_and_die("socket");
532 // Die with an error message if we can't bind a socket to an address.
533 void xbind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen)
535 if (bind(sockfd, my_addr, addrlen)) bb_perror_msg_and_die("bind");
538 // Die with an error message if we can't listen for connections on a socket.
539 void xlisten(int s, int backlog)
541 if (listen(s, backlog)) bb_perror_msg_and_die("listen");
544 // xstat() - a stat() which dies on failure with meaningful error message
545 void xstat(const char *name, struct stat *stat_buf)
547 if (stat(name, stat_buf))
548 bb_perror_msg_and_die("can't stat '%s'", name);
551 // selinux_or_die() - die if SELinux is disabled.
552 void selinux_or_die(void)
555 int rc = is_selinux_enabled();
557 bb_error_msg_and_die("SELinux is disabled");
559 bb_error_msg_and_die("is_selinux_enabled() failed");
562 bb_error_msg_and_die("SELinux support is disabled");
566 /* It is perfectly ok to pass in a NULL for either width or for
567 * height, in which case that value will not be set. */
568 int get_terminal_width_height(const int fd, int *width, int *height)
570 struct winsize win = { 0, 0, 0, 0 };
571 int ret = ioctl(fd, TIOCGWINSZ, &win);
575 char *s = getenv("LINES");
576 if (s) win.ws_row = atoi(s);
578 if (win.ws_row <= 1 || win.ws_row >= 30000)
580 *height = (int) win.ws_row;
585 char *s = getenv("COLUMNS");
586 if (s) win.ws_col = atoi(s);
588 if (win.ws_col <= 1 || win.ws_col >= 30000)
590 *width = (int) win.ws_col;