1 /* system-dependent definitions for coreutils
2 Copyright (C) 1989, 1991-2010 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/>. */
19 /* Include sys/types.h before this file. */
21 #if 2 <= __GLIBC__ && 2 <= __GLIBC_MINOR__
22 # if ! defined _SYS_TYPES_H
23 you must include
<sys
/types
.h
> before including
this file
29 #if !defined HAVE_MKFIFO
30 # define mkfifo(name, mode) mknod (name, (mode) | S_IFIFO, 0)
34 # include <sys/param.h>
39 /* limits.h must come before pathmax.h because limits.h on some systems
40 undefs PATH_MAX, whereas pathmax.h sets PATH_MAX. */
45 #include "configmake.h"
50 /* Since major is a function on SVR4, we can't use `ifndef major'. */
52 # include <sys/mkdev.h>
55 #if MAJOR_IN_SYSMACROS
56 # include <sys/sysmacros.h>
59 #ifdef major /* Might be defined in sys/types.h. */
64 # define major(dev) (((dev) >> 8) & 0xff)
65 # define minor(dev) ((dev) & 0xff)
66 # define makedev(maj, min) (((maj) << 8) | (min))
70 #if ! defined makedev && defined mkdev
71 # define makedev(maj, min) mkdev (maj, min)
74 /* Don't use bcopy! Use memmove if source and destination may overlap,
81 /* Some systems don't define this; POSIX mentions it but says it is
82 obsolete, so gnulib does not provide it either. */
91 /* Exit statuses for programs like 'env' that exec other programs. */
94 EXIT_TIMEDOUT
= 124, /* Time expired before child completed. */
95 EXIT_CANCELED
= 125, /* Internal error prior to exec attempt. */
96 EXIT_CANNOT_INVOKE
= 126, /* Program located, but not usable. */
97 EXIT_ENOENT
= 127 /* Could not find program to exec. */
100 #include "exitfail.h"
102 /* Set exit_failure to STATUS if that's not the default already. */
104 initialize_exit_failure (int status
)
106 if (status
!= EXIT_FAILURE
)
107 exit_failure
= status
;
113 #ifndef _D_EXACT_NAMLEN
114 # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name)
119 NOT_AN_INODE_NUMBER
= 0
122 #ifdef D_INO_IN_DIRENT
123 # define D_INO(dp) (dp)->d_ino
125 /* Some systems don't have inodes, so fake them to avoid lots of ifdefs. */
126 # define D_INO(dp) NOT_AN_INODE_NUMBER
129 /* include here for SIZE_MAX. */
130 #include <inttypes.h>
132 /* Get or fake the disk device blocksize.
133 Usually defined by sys/param.h (if at all). */
134 #if !defined DEV_BSIZE && defined BSIZE
135 # define DEV_BSIZE BSIZE
137 #if !defined DEV_BSIZE && defined BBSIZE /* SGI */
138 # define DEV_BSIZE BBSIZE
141 # define DEV_BSIZE 4096
144 /* Extract or fake data from a `struct stat'.
145 ST_BLKSIZE: Preferred I/O blocksize for the file, in bytes.
146 ST_NBLOCKS: Number of blocks in the file, including indirect blocks.
147 ST_NBLOCKSIZE: Size of blocks used when calculating ST_NBLOCKS. */
148 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
149 # define ST_BLKSIZE(statbuf) DEV_BSIZE
150 # if defined _POSIX_SOURCE || !defined BSIZE /* fileblocks.c uses BSIZE. */
151 # define ST_NBLOCKS(statbuf) \
152 ((statbuf).st_size / ST_NBLOCKSIZE + ((statbuf).st_size % ST_NBLOCKSIZE != 0))
153 # else /* !_POSIX_SOURCE && BSIZE */
154 # define ST_NBLOCKS(statbuf) \
155 (S_ISREG ((statbuf).st_mode) \
156 || S_ISDIR ((statbuf).st_mode) \
157 ? st_blocks ((statbuf).st_size) : 0)
158 # endif /* !_POSIX_SOURCE && BSIZE */
159 #else /* HAVE_STRUCT_STAT_ST_BLOCKS */
160 /* Some systems, like Sequents, return st_blksize of 0 on pipes.
161 Also, when running `rsh hpux11-system cat any-file', cat would
162 determine that the output stream had an st_blksize of 2147421096.
163 Conversely st_blksize can be 2 GiB (or maybe even larger) with XFS
164 on 64-bit hosts. Somewhat arbitrarily, limit the `optimal' block
165 size to SIZE_MAX / 8 + 1. (Dividing SIZE_MAX by only 4 wouldn't
166 suffice, since "cat" sometimes multiplies the result by 4.) If
167 anyone knows of a system for which this limit is too small, please
168 report it as a bug in this code. */
169 # define ST_BLKSIZE(statbuf) ((0 < (statbuf).st_blksize \
170 && (statbuf).st_blksize <= SIZE_MAX / 8 + 1) \
171 ? (statbuf).st_blksize : DEV_BSIZE)
172 # if defined hpux || defined __hpux__ || defined __hpux
173 /* HP-UX counts st_blocks in 1024-byte units.
174 This loses when mixing HP-UX and BSD file systems with NFS. */
175 # define ST_NBLOCKSIZE 1024
177 # if defined _AIX && defined _I386
178 /* AIX PS/2 counts st_blocks in 4K units. */
179 # define ST_NBLOCKSIZE (4 * 1024)
180 # else /* not AIX PS/2 */
182 # define ST_NBLOCKS(statbuf) \
183 (S_ISREG ((statbuf).st_mode) \
184 || S_ISDIR ((statbuf).st_mode) \
185 ? (statbuf).st_blocks * ST_BLKSIZE (statbuf) / ST_NBLOCKSIZE : 0)
187 # endif /* not AIX PS/2 */
189 #endif /* HAVE_STRUCT_STAT_ST_BLOCKS */
192 # define ST_NBLOCKS(statbuf) ((statbuf).st_blocks)
195 #ifndef ST_NBLOCKSIZE
197 # define ST_NBLOCKSIZE S_BLKSIZE
199 # define ST_NBLOCKSIZE 512
203 /* Redirection and wildcarding when done by the utility itself.
204 Generally a noop, but used in particular for native VMS. */
205 #ifndef initialize_main
206 # define initialize_main(ac, av)
209 #include "stat-macros.h"
211 #include "timespec.h"
215 /* ISDIGIT differs from isdigit, as follows:
216 - Its arg may be any int or unsigned int; it need not be an unsigned char
218 - It's typically faster.
219 POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
220 isdigit unless it's important to use the locale's definition
221 of `digit' even when the host does not conform to POSIX. */
222 #define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
224 /* Convert a possibly-signed character to an unsigned character. This is
225 a bit safer than casting to unsigned char, since it catches some type
226 errors that the cast doesn't. */
227 static inline unsigned char to_uchar (char ch
) { return ch
; }
231 /* Take care of NLS matters. */
236 # define textdomain(Domainname) /* empty */
237 # undef bindtextdomain
238 # define bindtextdomain(Domainname, Dirname) /* empty */
241 #define _(msgid) gettext (msgid)
242 #define N_(msgid) msgid
244 /* Return a value that pluralizes the same way that N does, in all
245 languages we know of. */
246 static inline unsigned long int
247 select_plural (uintmax_t n
)
249 /* Reduce by a power of ten, but keep it away from zero. The
250 gettext manual says 1000000 should be safe. */
251 enum { PLURAL_REDUCER
= 1000000 };
252 return (n
<= ULONG_MAX
? n
: n
% PLURAL_REDUCER
+ PLURAL_REDUCER
);
255 #define STREQ(a, b) (strcmp (a, b) == 0)
257 #if !HAVE_DECL_GETLOGIN
261 #if !HAVE_DECL_TTYNAME
265 #if !HAVE_DECL_GETEUID
269 #if !HAVE_DECL_GETPWUID
270 struct passwd
*getpwuid ();
273 #if !HAVE_DECL_GETGRGID
274 struct group
*getgrgid ();
277 #if !HAVE_DECL_GETUID
284 /* This is simply a shorthand for the common case in which
285 the third argument to x2nrealloc would be `sizeof *(P)'.
286 Ensure that sizeof *(P) is *not* 1. In that case, it'd be
287 better to use X2REALLOC, although not strictly necessary. */
288 #define X2NREALLOC(P, PN) ((void) verify_true (sizeof *(P) != 1), \
289 x2nrealloc (P, PN, sizeof *(P)))
291 /* Using x2realloc (when appropriate) usually makes your code more
292 readable than using x2nrealloc, but it also makes it so your
293 code will malfunction if sizeof *(P) ever becomes 2 or greater.
294 So use this macro instead of using x2realloc directly. */
295 #define X2REALLOC(P, PN) ((void) verify_true (sizeof *(P) == 1), \
298 #include "unlocked-io.h"
299 #include "same-inode.h"
305 dot_or_dotdot (char const *file_name
)
307 if (file_name
[0] == '.')
309 char sep
= file_name
[(file_name
[1] == '.') + 1];
310 return (! sep
|| ISSLASH (sep
));
316 /* A wrapper for readdir so that callers don't see entries for `.' or `..'. */
317 static inline struct dirent
const *
318 readdir_ignoring_dot_and_dotdot (DIR *dirp
)
322 struct dirent
const *dp
= readdir (dirp
);
323 if (dp
== NULL
|| ! dot_or_dotdot (dp
->d_name
))
328 /* Return true if DIR is determined to be an empty directory. */
330 is_empty_dir (int fd_cwd
, char const *dir
)
333 struct dirent
const *dp
;
335 int fd
= openat (fd_cwd
, dir
,
336 (O_RDONLY
| O_DIRECTORY
337 | O_NOCTTY
| O_NOFOLLOW
| O_NONBLOCK
));
342 dirp
= fdopendir (fd
);
350 dp
= readdir_ignoring_dot_and_dotdot (dirp
);
355 return saved_errno
== 0 ? true : false;
358 /* Factor out some of the common --help and --version processing code. */
360 /* These enum values cannot possibly conflict with the option values
361 ordinarily used by commands, including CHAR_MAX + 1, etc. Avoid
362 CHAR_MIN - 1, as it may equal -1, the getopt end-of-options value. */
365 GETOPT_HELP_CHAR
= (CHAR_MIN
- 2),
366 GETOPT_VERSION_CHAR
= (CHAR_MIN
- 3)
369 #define GETOPT_HELP_OPTION_DECL \
370 "help", no_argument, NULL, GETOPT_HELP_CHAR
371 #define GETOPT_VERSION_OPTION_DECL \
372 "version", no_argument, NULL, GETOPT_VERSION_CHAR
373 #define GETOPT_SELINUX_CONTEXT_OPTION_DECL \
374 "context", required_argument, NULL, 'Z'
376 #define case_GETOPT_HELP_CHAR \
377 case GETOPT_HELP_CHAR: \
378 usage (EXIT_SUCCESS); \
381 /* Program_name must be a literal string.
382 Usually it is just PROGRAM_NAME. */
383 #define USAGE_BUILTIN_WARNING \
385 "NOTE: your shell may have its own version of %s, which usually supersedes\n" \
386 "the version described here. Please refer to your shell's documentation\n" \
387 "for details about the options it supports.\n")
389 #define HELP_OPTION_DESCRIPTION \
390 _(" --help display this help and exit\n")
391 #define VERSION_OPTION_DESCRIPTION \
392 _(" --version output version information and exit\n")
395 #include "closeout.h"
397 #define emit_bug_reporting_address unused__emit_bug_reporting_address
398 #include "version-etc.h"
399 #undef emit_bug_reporting_address
401 #include "propername.h"
402 /* Define away proper_name (leaving proper_name_utf8, which affects far
403 fewer programs), since it's not worth the cost of adding ~17KB to
404 the x86_64 text size of every single program. This avoids a 40%
405 (almost ~2MB) increase in the on-disk space utilization for the set
406 of the 100 binaries. */
407 #define proper_name(x) (x)
409 #include "progname.h"
411 #define case_GETOPT_VERSION_CHAR(Program_name, Authors) \
412 case GETOPT_VERSION_CHAR: \
413 version_etc (stdout, Program_name, PACKAGE_NAME, Version, Authors, \
415 exit (EXIT_SUCCESS); \
419 # define MAX(a, b) ((a) > (b) ? (a) : (b))
423 # define MIN(a,b) (((a) < (b)) ? (a) : (b))
426 #include "intprops.h"
429 # define SSIZE_MAX TYPE_MAXIMUM (ssize_t)
433 # define OFF_T_MIN TYPE_MINIMUM (off_t)
437 # define OFF_T_MAX TYPE_MAXIMUM (off_t)
441 # define UID_T_MAX TYPE_MAXIMUM (uid_t)
445 # define GID_T_MAX TYPE_MAXIMUM (gid_t)
449 # define PID_T_MAX TYPE_MAXIMUM (pid_t)
452 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
454 # define IF_LINT(Code) Code
456 # define IF_LINT(Code) /* empty */
459 /* With -Dlint, avoid warnings from gcc about code like mbstate_t m = {0,};
460 by wasting space on a static variable of the same type, that is thus
461 guaranteed to be initialized to 0, and use that on the RHS. */
462 #define DZA_CONCAT0(x,y) x ## y
463 #define DZA_CONCAT(x,y) DZA_CONCAT0 (x, y)
465 # define DECLARE_ZEROED_AGGREGATE(Type, Var) \
466 static Type DZA_CONCAT (s0_, __LINE__); Type Var = DZA_CONCAT (s0_, __LINE__)
468 # define DECLARE_ZEROED_AGGREGATE(Type, Var) \
472 #ifndef __attribute__
473 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8)
474 # define __attribute__(x) /* empty */
478 #ifndef ATTRIBUTE_NORETURN
479 # define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
482 #ifndef ATTRIBUTE_UNUSED
483 # define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
486 /* The warn_unused_result attribute appeared first in gcc-3.4.0 */
487 #undef ATTRIBUTE_WARN_UNUSED_RESULT
488 #if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)
489 # define ATTRIBUTE_WARN_UNUSED_RESULT /* empty */
491 # define ATTRIBUTE_WARN_UNUSED_RESULT __attribute__ ((__warn_unused_result__))
495 # define ASSIGN_STRDUPA(DEST, S) \
496 do { DEST = strdupa (S); } while (0)
498 # define ASSIGN_STRDUPA(DEST, S) \
501 const char *s_ = (S); \
502 size_t len_ = strlen (s_) + 1; \
503 char *tmp_dest_ = alloca (len_); \
504 DEST = memcpy (tmp_dest_, s_, len_); \
510 # define sync() /* empty */
513 /* Compute the greatest common divisor of U and V using Euclid's
514 algorithm. U and V must be nonzero. */
517 gcd (size_t u
, size_t v
)
530 /* Compute the least common multiple of U and V. U and V must be
531 nonzero. There is no overflow checking, so callers should not
532 specify outlandish sizes. */
535 lcm (size_t u
, size_t v
)
537 return u
* (v
/ gcd (u
, v
));
540 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
541 ALIGNMENT must be nonzero. The caller must arrange for ((char *)
542 PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
546 ptr_align (void const *ptr
, size_t alignment
)
548 char const *p0
= ptr
;
549 char const *p1
= p0
+ alignment
- 1;
550 return (void *) (p1
- (size_t) p1
% alignment
);
553 /* If 10*Accum + Digit_val is larger than the maximum value for Type,
554 then don't update Accum and return false to indicate it would
555 overflow. Otherwise, set Accum to that new value and return true.
556 Verify at compile-time that Type is Accum's type, and that Type is
557 unsigned. Accum must be an object, so that we can take its
558 address. Accum and Digit_val may be evaluated multiple times.
560 The "Added check" below is not strictly required, but it causes GCC
561 to return a nonzero exit status instead of merely a warning
562 diagnostic, and that is more useful. */
564 #define DECIMAL_DIGIT_ACCUMULATE(Accum, Digit_val, Type) \
566 (void) (&(Accum) == (Type *) NULL), /* The type matches. */ \
567 (void) verify_true (! TYPE_SIGNED (Type)), /* The type is unsigned. */ \
568 (void) verify_true (sizeof (Accum) == sizeof (Type)), /* Added check. */ \
569 (((Type) -1 / 10 < (Accum) \
570 || (Type) ((Accum) * 10 + (Digit_val)) < (Accum)) \
571 ? false : (((Accum) = (Accum) * 10 + (Digit_val)), true)) \
575 emit_size_note (void)
578 SIZE may be (or may be an integer optionally followed by) one of following:\n\
579 KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
584 emit_blocksize_note (char const *program
)
587 Display values are in units of the first available SIZE from --block-size,\n\
588 and the %s_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables.\n\
589 Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set).\n\
594 emit_ancillary_info (void)
596 printf (_("\nReport %s bugs to %s\n"), last_component (program_name
),
598 /* FIXME 2010: use AC_PACKAGE_URL once we require autoconf-2.64 */
599 printf (_("%s home page: <http://www.gnu.org/software/%s/>\n"),
600 PACKAGE_NAME
, PACKAGE
);
601 fputs (_("General help using GNU software: <http://www.gnu.org/gethelp/>\n"),
603 /* Don't output this redundant message for English locales.
604 Note we still output for 'C' so that it gets included in the man page. */
605 const char *lc_messages
= setlocale (LC_MESSAGES
, NULL
);
606 if (lc_messages
&& strncmp (lc_messages
, "en_", 3))
608 /* TRANSLATORS: Replace LANG_CODE in this URL with your language code
609 <http://translationproject.org/team/LANG_CODE.html> to form one of
610 the URLs at http://translationproject.org/team/. Otherwise, replace
611 the entire URL with your translation team's email address. */
612 printf (_("Report %s translation bugs to "
613 "<http://translationproject.org/team/>\n"),
614 last_component (program_name
));
616 printf (_("For complete documentation, run: "
617 "info coreutils '%s invocation'\n"), last_component (program_name
));
620 #include "inttostr.h"
623 timetostr (time_t t
, char *buf
)
625 return (TYPE_SIGNED (time_t)
627 : umaxtostr (t
, buf
));
631 bad_cast (char const *s
)
636 /* As of Mar 2009, 32KiB is determined to be the minimium
637 blksize to best minimize system call overhead.
638 This can be tested with this script with the results
639 shown for a 1.7GHz pentium-m with 2GB of 400MHz DDR2 RAM:
641 for i in $(seq 0 10); do
642 size=$((8*1024**3)) #ensure this is big enough
645 dd bs=$bs if=/dev/zero of=/dev/null count=$(($size/$bs)) 2>&1 |
646 sed -n 's/.* \([0-9.]* [GM]B\/s\)/\1/p'
661 Note that this is to minimize system call overhead.
662 Other values may be appropriate to minimize file system
663 or disk overhead. For example on my current GNU/Linux system
664 the readahead setting is 128KiB which was read using:
667 device=$(df -P --local "$file" | tail -n1 | cut -d' ' -f1)
668 echo $(( $(blockdev --getra $device) * 512 ))
670 However there isn't a portable way to get the above.
671 In the future we could use the above method if available
672 and default to io_blksize() if not.
674 enum { IO_BUFSIZE
= 32*1024 };
676 io_blksize (struct stat sb
)
678 return MAX (IO_BUFSIZE
, ST_BLKSIZE (sb
));
681 void usage (int status
) ATTRIBUTE_NORETURN
;
683 #define emit_cycle_warning(file_name) \
687 WARNING: Circular directory structure.\n\
688 This almost certainly means that you have a corrupted file system.\n\
689 NOTIFY YOUR SYSTEM MANAGER.\n\
690 The following directory is part of the cycle:\n %s\n"), \
691 quote (file_name)); \
695 #ifndef ARRAY_CARDINALITY
696 # define ARRAY_CARDINALITY(Array) (sizeof (Array) / sizeof *(Array))