1 /* system-dependent definitions for coreutils
2 Copyright (C) 1989, 1991-2011 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Include this file _after_ system headers if possible. */
21 /* Include <sys/types.h> before this file.
22 Note this doesn't warn if we're included
23 before all system headers. */
25 #if 2 < __GLIBC__ || ( 2 == ___GLIBC__ && 2 <= __GLIBC_MINOR__ )
26 # if ! defined _SYS_TYPES_H
27 you must include <sys/types.h> before including this file
33 #if !defined HAVE_MKFIFO
34 # define mkfifo(name, mode) mknod (name, (mode) | S_IFIFO, 0)
38 # include <sys/param.h>
43 /* limits.h must come before pathmax.h because limits.h on some systems
44 undefs PATH_MAX, whereas pathmax.h sets PATH_MAX. */
49 #include "configmake.h"
54 /* Since major is a function on SVR4, we can't use `ifndef major'. */
56 # include <sys/mkdev.h>
59 #if MAJOR_IN_SYSMACROS
60 # include <sys/sysmacros.h>
63 #ifdef major /* Might be defined in sys/types.h. */
68 # define major(dev) (((dev) >> 8) & 0xff)
69 # define minor(dev) ((dev) & 0xff)
70 # define makedev(maj, min) (((maj) << 8) | (min))
74 #if ! defined makedev && defined mkdev
75 # define makedev(maj, min) mkdev (maj, min)
78 /* Don't use bcopy! Use memmove if source and destination may overlap,
85 /* Some systems don't define this; POSIX mentions it but says it is
86 obsolete, so gnulib does not provide it either. */
95 /* Exit statuses for programs like 'env' that exec other programs. */
98 EXIT_TIMEDOUT = 124, /* Time expired before child completed. */
99 EXIT_CANCELED = 125, /* Internal error prior to exec attempt. */
100 EXIT_CANNOT_INVOKE = 126, /* Program located, but not usable. */
101 EXIT_ENOENT = 127 /* Could not find program to exec. */
104 #include "exitfail.h"
106 /* Set exit_failure to STATUS if that's not the default already. */
108 initialize_exit_failure (int status)
110 if (status != EXIT_FAILURE)
111 exit_failure = status;
117 #ifndef _D_EXACT_NAMLEN
118 # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name)
123 NOT_AN_INODE_NUMBER = 0
126 #ifdef D_INO_IN_DIRENT
127 # define D_INO(dp) (dp)->d_ino
129 /* Some systems don't have inodes, so fake them to avoid lots of ifdefs. */
130 # define D_INO(dp) NOT_AN_INODE_NUMBER
133 /* include here for SIZE_MAX. */
134 #include <inttypes.h>
136 /* Get or fake the disk device blocksize.
137 Usually defined by sys/param.h (if at all). */
138 #if !defined DEV_BSIZE && defined BSIZE
139 # define DEV_BSIZE BSIZE
141 #if !defined DEV_BSIZE && defined BBSIZE /* SGI */
142 # define DEV_BSIZE BBSIZE
145 # define DEV_BSIZE 4096
148 /* Extract or fake data from a `struct stat'.
149 ST_BLKSIZE: Preferred I/O blocksize for the file, in bytes.
150 ST_NBLOCKS: Number of blocks in the file, including indirect blocks.
151 ST_NBLOCKSIZE: Size of blocks used when calculating ST_NBLOCKS. */
152 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
153 # define ST_BLKSIZE(statbuf) DEV_BSIZE
154 # if defined _POSIX_SOURCE || !defined BSIZE /* fileblocks.c uses BSIZE. */
155 # define ST_NBLOCKS(statbuf) \
156 ((statbuf).st_size / ST_NBLOCKSIZE + ((statbuf).st_size % ST_NBLOCKSIZE != 0))
157 # else /* !_POSIX_SOURCE && BSIZE */
158 # define ST_NBLOCKS(statbuf) \
159 (S_ISREG ((statbuf).st_mode) \
160 || S_ISDIR ((statbuf).st_mode) \
161 ? st_blocks ((statbuf).st_size) : 0)
162 # endif /* !_POSIX_SOURCE && BSIZE */
163 #else /* HAVE_STRUCT_STAT_ST_BLOCKS */
164 /* Some systems, like Sequents, return st_blksize of 0 on pipes.
165 Also, when running `rsh hpux11-system cat any-file', cat would
166 determine that the output stream had an st_blksize of 2147421096.
167 Conversely st_blksize can be 2 GiB (or maybe even larger) with XFS
168 on 64-bit hosts. Somewhat arbitrarily, limit the `optimal' block
169 size to SIZE_MAX / 8 + 1. (Dividing SIZE_MAX by only 4 wouldn't
170 suffice, since "cat" sometimes multiplies the result by 4.) If
171 anyone knows of a system for which this limit is too small, please
172 report it as a bug in this code. */
173 # define ST_BLKSIZE(statbuf) ((0 < (statbuf).st_blksize \
174 && (statbuf).st_blksize <= SIZE_MAX / 8 + 1) \
175 ? (statbuf).st_blksize : DEV_BSIZE)
176 # if defined hpux || defined __hpux__ || defined __hpux
177 /* HP-UX counts st_blocks in 1024-byte units.
178 This loses when mixing HP-UX and BSD file systems with NFS. */
179 # define ST_NBLOCKSIZE 1024
181 # if defined _AIX && defined _I386
182 /* AIX PS/2 counts st_blocks in 4K units. */
183 # define ST_NBLOCKSIZE (4 * 1024)
184 # else /* not AIX PS/2 */
186 # define ST_NBLOCKS(statbuf) \
187 (S_ISREG ((statbuf).st_mode) \
188 || S_ISDIR ((statbuf).st_mode) \
189 ? (statbuf).st_blocks * ST_BLKSIZE (statbuf) / ST_NBLOCKSIZE : 0)
191 # endif /* not AIX PS/2 */
193 #endif /* HAVE_STRUCT_STAT_ST_BLOCKS */
196 # define ST_NBLOCKS(statbuf) ((statbuf).st_blocks)
199 #ifndef ST_NBLOCKSIZE
201 # define ST_NBLOCKSIZE S_BLKSIZE
203 # define ST_NBLOCKSIZE 512
207 /* Redirection and wildcarding when done by the utility itself.
208 Generally a noop, but used in particular for native VMS. */
209 #ifndef initialize_main
210 # define initialize_main(ac, av)
213 #include "stat-macros.h"
215 #include "timespec.h"
219 /* ISDIGIT differs from isdigit, as follows:
220 - Its arg may be any int or unsigned int; it need not be an unsigned char
222 - It's typically faster.
223 POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
224 isdigit unless it's important to use the locale's definition
225 of `digit' even when the host does not conform to POSIX. */
226 #define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
228 /* Convert a possibly-signed character to an unsigned character. This is
229 a bit safer than casting to unsigned char, since it catches some type
230 errors that the cast doesn't. */
231 static inline unsigned char to_uchar (char ch) { return ch; }
235 /* Take care of NLS matters. */
240 # define textdomain(Domainname) /* empty */
241 # undef bindtextdomain
242 # define bindtextdomain(Domainname, Dirname) /* empty */
245 #define _(msgid) gettext (msgid)
246 #define N_(msgid) msgid
248 /* Return a value that pluralizes the same way that N does, in all
249 languages we know of. */
250 static inline unsigned long int
251 select_plural (uintmax_t n)
253 /* Reduce by a power of ten, but keep it away from zero. The
254 gettext manual says 1000000 should be safe. */
255 enum { PLURAL_REDUCER = 1000000 };
256 return (n <= ULONG_MAX ? n : n % PLURAL_REDUCER + PLURAL_REDUCER);
259 #define STREQ(a, b) (strcmp (a, b) == 0)
260 #define STREQ_LEN(a, b, n) (strncmp (a, b, n) == 0)
261 #define STRPREFIX(a, b) (strncmp(a, b, strlen (b)) == 0)
263 /* Just like strncmp, but the first argument must be a literal string
264 and you don't specify the length. */
265 #define STRNCMP_LIT(s, literal) \
266 strncmp (s, "" literal "", sizeof (literal) - 1)
268 #if !HAVE_DECL_GETLOGIN
272 #if !HAVE_DECL_TTYNAME
276 #if !HAVE_DECL_GETEUID
280 #if !HAVE_DECL_GETPWUID
281 struct passwd *getpwuid ();
284 #if !HAVE_DECL_GETGRGID
285 struct group *getgrgid ();
288 #if !HAVE_DECL_GETUID
295 /* This is simply a shorthand for the common case in which
296 the third argument to x2nrealloc would be `sizeof *(P)'.
297 Ensure that sizeof *(P) is *not* 1. In that case, it'd be
298 better to use X2REALLOC, although not strictly necessary. */
299 #define X2NREALLOC(P, PN) ((void) verify_true (sizeof *(P) != 1), \
300 x2nrealloc (P, PN, sizeof *(P)))
302 /* Using x2realloc (when appropriate) usually makes your code more
303 readable than using x2nrealloc, but it also makes it so your
304 code will malfunction if sizeof *(P) ever becomes 2 or greater.
305 So use this macro instead of using x2realloc directly. */
306 #define X2REALLOC(P, PN) ((void) verify_true (sizeof *(P) == 1), \
309 #include "unlocked-io.h"
310 #include "same-inode.h"
316 dot_or_dotdot (char const *file_name)
318 if (file_name[0] == '.')
320 char sep = file_name[(file_name[1] == '.') + 1];
321 return (! sep || ISSLASH (sep));
327 /* A wrapper for readdir so that callers don't see entries for `.' or `..'. */
328 static inline struct dirent const *
329 readdir_ignoring_dot_and_dotdot (DIR *dirp)
333 struct dirent const *dp = readdir (dirp);
334 if (dp == NULL || ! dot_or_dotdot (dp->d_name))
339 /* Return true if DIR is determined to be an empty directory. */
341 is_empty_dir (int fd_cwd, char const *dir)
344 struct dirent const *dp;
346 int fd = openat (fd_cwd, dir,
347 (O_RDONLY | O_DIRECTORY
348 | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK));
353 dirp = fdopendir (fd);
361 dp = readdir_ignoring_dot_and_dotdot (dirp);
366 return saved_errno == 0 ? true : false;
369 /* Factor out some of the common --help and --version processing code. */
371 /* These enum values cannot possibly conflict with the option values
372 ordinarily used by commands, including CHAR_MAX + 1, etc. Avoid
373 CHAR_MIN - 1, as it may equal -1, the getopt end-of-options value. */
376 GETOPT_HELP_CHAR = (CHAR_MIN - 2),
377 GETOPT_VERSION_CHAR = (CHAR_MIN - 3)
380 #define GETOPT_HELP_OPTION_DECL \
381 "help", no_argument, NULL, GETOPT_HELP_CHAR
382 #define GETOPT_VERSION_OPTION_DECL \
383 "version", no_argument, NULL, GETOPT_VERSION_CHAR
384 #define GETOPT_SELINUX_CONTEXT_OPTION_DECL \
385 "context", required_argument, NULL, 'Z'
387 #define case_GETOPT_HELP_CHAR \
388 case GETOPT_HELP_CHAR: \
389 usage (EXIT_SUCCESS); \
392 /* Program_name must be a literal string.
393 Usually it is just PROGRAM_NAME. */
394 #define USAGE_BUILTIN_WARNING \
396 "NOTE: your shell may have its own version of %s, which usually supersedes\n" \
397 "the version described here. Please refer to your shell's documentation\n" \
398 "for details about the options it supports.\n")
400 #define HELP_OPTION_DESCRIPTION \
401 _(" --help display this help and exit\n")
402 #define VERSION_OPTION_DESCRIPTION \
403 _(" --version output version information and exit\n")
406 #include "closeout.h"
408 #define emit_bug_reporting_address unused__emit_bug_reporting_address
409 #include "version-etc.h"
410 #undef emit_bug_reporting_address
412 #include "propername.h"
413 /* Define away proper_name (leaving proper_name_utf8, which affects far
414 fewer programs), since it's not worth the cost of adding ~17KB to
415 the x86_64 text size of every single program. This avoids a 40%
416 (almost ~2MB) increase in the on-disk space utilization for the set
417 of the 100 binaries. */
418 #define proper_name(x) (x)
420 #include "progname.h"
422 #define case_GETOPT_VERSION_CHAR(Program_name, Authors) \
423 case GETOPT_VERSION_CHAR: \
424 version_etc (stdout, Program_name, PACKAGE_NAME, Version, Authors, \
426 exit (EXIT_SUCCESS); \
430 # define MAX(a, b) ((a) > (b) ? (a) : (b))
434 # define MIN(a,b) (((a) < (b)) ? (a) : (b))
437 #include "intprops.h"
440 # define SSIZE_MAX TYPE_MAXIMUM (ssize_t)
444 # define OFF_T_MIN TYPE_MINIMUM (off_t)
448 # define OFF_T_MAX TYPE_MAXIMUM (off_t)
452 # define UID_T_MAX TYPE_MAXIMUM (uid_t)
456 # define GID_T_MAX TYPE_MAXIMUM (gid_t)
460 # define PID_T_MAX TYPE_MAXIMUM (pid_t)
463 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
465 # define IF_LINT(Code) Code
467 # define IF_LINT(Code) /* empty */
470 #ifndef __attribute__
471 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8)
472 # define __attribute__(x) /* empty */
476 #ifndef ATTRIBUTE_NORETURN
477 # define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
480 #ifndef ATTRIBUTE_UNUSED
481 # define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
484 /* The warn_unused_result attribute appeared first in gcc-3.4.0 */
485 #undef ATTRIBUTE_WARN_UNUSED_RESULT
486 #if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)
487 # define ATTRIBUTE_WARN_UNUSED_RESULT /* empty */
489 # define ATTRIBUTE_WARN_UNUSED_RESULT __attribute__ ((__warn_unused_result__))
493 # define ASSIGN_STRDUPA(DEST, S) \
494 do { DEST = strdupa (S); } while (0)
496 # define ASSIGN_STRDUPA(DEST, S) \
499 const char *s_ = (S); \
500 size_t len_ = strlen (s_) + 1; \
501 char *tmp_dest_ = alloca (len_); \
502 DEST = memcpy (tmp_dest_, s_, len_); \
508 # define sync() /* empty */
511 /* Compute the greatest common divisor of U and V using Euclid's
512 algorithm. U and V must be nonzero. */
515 gcd (size_t u, size_t v)
528 /* Compute the least common multiple of U and V. U and V must be
529 nonzero. There is no overflow checking, so callers should not
530 specify outlandish sizes. */
533 lcm (size_t u, size_t v)
535 return u * (v / gcd (u, v));
538 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
539 ALIGNMENT must be nonzero. The caller must arrange for ((char *)
540 PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
544 ptr_align (void const *ptr, size_t alignment)
546 char const *p0 = ptr;
547 char const *p1 = p0 + alignment - 1;
548 return (void *) (p1 - (size_t) p1 % alignment);
551 /* If 10*Accum + Digit_val is larger than the maximum value for Type,
552 then don't update Accum and return false to indicate it would
553 overflow. Otherwise, set Accum to that new value and return true.
554 Verify at compile-time that Type is Accum's type, and that Type is
555 unsigned. Accum must be an object, so that we can take its
556 address. Accum and Digit_val may be evaluated multiple times.
558 The "Added check" below is not strictly required, but it causes GCC
559 to return a nonzero exit status instead of merely a warning
560 diagnostic, and that is more useful. */
562 #define DECIMAL_DIGIT_ACCUMULATE(Accum, Digit_val, Type) \
564 (void) (&(Accum) == (Type *) NULL), /* The type matches. */ \
565 (void) verify_true (! TYPE_SIGNED (Type)), /* The type is unsigned. */ \
566 (void) verify_true (sizeof (Accum) == sizeof (Type)), /* Added check. */ \
567 (((Type) -1 / 10 < (Accum) \
568 || (Type) ((Accum) * 10 + (Digit_val)) < (Accum)) \
569 ? false : (((Accum) = (Accum) * 10 + (Digit_val)), true)) \
573 emit_size_note (void)
576 SIZE may be (or may be an integer optionally followed by) one of following:\n\
577 KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
582 emit_blocksize_note (char const *program)
585 Display values are in units of the first available SIZE from --block-size,\n\
586 and the %s_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables.\n\
587 Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set).\n\
592 emit_ancillary_info (void)
594 printf (_("\nReport %s bugs to %s\n"), last_component (program_name),
596 /* FIXME 2010: use AC_PACKAGE_URL once we require autoconf-2.64 */
597 printf (_("%s home page: <http://www.gnu.org/software/%s/>\n"),
598 PACKAGE_NAME, PACKAGE);
599 fputs (_("General help using GNU software: <http://www.gnu.org/gethelp/>\n"),
601 /* Don't output this redundant message for English locales.
602 Note we still output for 'C' so that it gets included in the man page. */
603 const char *lc_messages = setlocale (LC_MESSAGES, NULL);
604 if (lc_messages && STRNCMP_LIT (lc_messages, "en_"))
606 /* TRANSLATORS: Replace LANG_CODE in this URL with your language code
607 <http://translationproject.org/team/LANG_CODE.html> to form one of
608 the URLs at http://translationproject.org/team/. Otherwise, replace
609 the entire URL with your translation team's email address. */
610 printf (_("Report %s translation bugs to "
611 "<http://translationproject.org/team/>\n"),
612 last_component (program_name));
614 printf (_("For complete documentation, run: "
615 "info coreutils '%s invocation'\n"), last_component (program_name));
618 #include "inttostr.h"
621 timetostr (time_t t, char *buf)
623 return (TYPE_SIGNED (time_t)
625 : umaxtostr (t, buf));
629 bad_cast (char const *s)
634 /* As of Mar 2009, 32KiB is determined to be the minimium
635 blksize to best minimize system call overhead.
636 This can be tested with this script with the results
637 shown for a 1.7GHz pentium-m with 2GB of 400MHz DDR2 RAM:
639 for i in $(seq 0 10); do
640 size=$((8*1024**3)) #ensure this is big enough
643 dd bs=$bs if=/dev/zero of=/dev/null count=$(($size/$bs)) 2>&1 |
644 sed -n 's/.* \([0-9.]* [GM]B\/s\)/\1/p'
659 Note that this is to minimize system call overhead.
660 Other values may be appropriate to minimize file system
661 or disk overhead. For example on my current GNU/Linux system
662 the readahead setting is 128KiB which was read using:
665 device=$(df -P --local "$file" | tail -n1 | cut -d' ' -f1)
666 echo $(( $(blockdev --getra $device) * 512 ))
668 However there isn't a portable way to get the above.
669 In the future we could use the above method if available
670 and default to io_blksize() if not.
672 enum { IO_BUFSIZE = 32*1024 };
674 io_blksize (struct stat sb)
676 return MAX (IO_BUFSIZE, ST_BLKSIZE (sb));
679 void usage (int status) ATTRIBUTE_NORETURN;
681 #define emit_cycle_warning(file_name) \
685 WARNING: Circular directory structure.\n\
686 This almost certainly means that you have a corrupted file system.\n\
687 NOTIFY YOUR SYSTEM MANAGER.\n\
688 The following directory is part of the cycle:\n %s\n"), \
689 quote (file_name)); \
693 #ifndef ARRAY_CARDINALITY
694 # define ARRAY_CARDINALITY(Array) (sizeof (Array) / sizeof *(Array))