global: convert indentation-TABs to spaces
[coreutils.git] / src / system.h
blob3a0550122658ea7e8872bad54c23190324c90cca
1 /* system-dependent definitions for coreutils
2 Copyright (C) 1989, 1991-2009 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 <alloca.h>
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
24 # endif
25 #endif
27 #include <sys/stat.h>
29 #if !defined HAVE_MKFIFO
30 # define mkfifo(name, mode) mknod (name, (mode) | S_IFIFO, 0)
31 #endif
33 #if HAVE_SYS_PARAM_H
34 # include <sys/param.h>
35 #endif
37 #include <unistd.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. */
41 #include <limits.h>
43 #include "pathmax.h"
45 #include "configmake.h"
47 #if TIME_WITH_SYS_TIME
48 # include <sys/time.h>
49 # include <time.h>
50 #else
51 # if HAVE_SYS_TIME_H
52 # include <sys/time.h>
53 # else
54 # include <time.h>
55 # endif
56 #endif
58 /* Since major is a function on SVR4, we can't use `ifndef major'. */
59 #if MAJOR_IN_MKDEV
60 # include <sys/mkdev.h>
61 # define HAVE_MAJOR
62 #endif
63 #if MAJOR_IN_SYSMACROS
64 # include <sys/sysmacros.h>
65 # define HAVE_MAJOR
66 #endif
67 #ifdef major /* Might be defined in sys/types.h. */
68 # define HAVE_MAJOR
69 #endif
71 #ifndef HAVE_MAJOR
72 # define major(dev) (((dev) >> 8) & 0xff)
73 # define minor(dev) ((dev) & 0xff)
74 # define makedev(maj, min) (((maj) << 8) | (min))
75 #endif
76 #undef HAVE_MAJOR
78 #if ! defined makedev && defined mkdev
79 # define makedev(maj, min) mkdev (maj, min)
80 #endif
82 /* Don't use bcopy! Use memmove if source and destination may overlap,
83 memcpy otherwise. */
85 #include <string.h>
87 #include <errno.h>
89 /* Some systems don't define the following symbols. */
90 #ifndef EDQUOT
91 # define EDQUOT (-1)
92 #endif
93 #ifndef EISDIR
94 # define EISDIR (-1)
95 #endif
96 #ifndef ENOSYS
97 # define ENOSYS (-1)
98 #endif
99 #ifndef ENODATA
100 # define ENODATA (-1)
101 #endif
103 #include <stdbool.h>
104 #include <stdlib.h>
105 #include "version.h"
107 /* Exit statuses for programs like 'env' that exec other programs. */
108 enum
110 EXIT_CANNOT_INVOKE = 126,
111 EXIT_ENOENT = 127
114 #include "exitfail.h"
116 /* Set exit_failure to STATUS if that's not the default already. */
117 static inline void
118 initialize_exit_failure (int status)
120 if (status != EXIT_FAILURE)
121 exit_failure = status;
124 #include <fcntl.h>
126 #ifndef F_OK
127 # define F_OK 0
128 # define X_OK 1
129 # define W_OK 2
130 # define R_OK 4
131 #endif
133 #include <dirent.h>
134 #ifndef _D_EXACT_NAMLEN
135 # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name)
136 #endif
138 enum
140 NOT_AN_INODE_NUMBER = 0
143 #ifdef D_INO_IN_DIRENT
144 # define D_INO(dp) (dp)->d_ino
145 #else
146 /* Some systems don't have inodes, so fake them to avoid lots of ifdefs. */
147 # define D_INO(dp) NOT_AN_INODE_NUMBER
148 #endif
150 /* include here for SIZE_MAX. */
151 #include <inttypes.h>
153 /* Get or fake the disk device blocksize.
154 Usually defined by sys/param.h (if at all). */
155 #if !defined DEV_BSIZE && defined BSIZE
156 # define DEV_BSIZE BSIZE
157 #endif
158 #if !defined DEV_BSIZE && defined BBSIZE /* SGI */
159 # define DEV_BSIZE BBSIZE
160 #endif
161 #ifndef DEV_BSIZE
162 # define DEV_BSIZE 4096
163 #endif
165 /* Extract or fake data from a `struct stat'.
166 ST_BLKSIZE: Preferred I/O blocksize for the file, in bytes.
167 ST_NBLOCKS: Number of blocks in the file, including indirect blocks.
168 ST_NBLOCKSIZE: Size of blocks used when calculating ST_NBLOCKS. */
169 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
170 # define ST_BLKSIZE(statbuf) DEV_BSIZE
171 # if defined _POSIX_SOURCE || !defined BSIZE /* fileblocks.c uses BSIZE. */
172 # define ST_NBLOCKS(statbuf) \
173 ((statbuf).st_size / ST_NBLOCKSIZE + ((statbuf).st_size % ST_NBLOCKSIZE != 0))
174 # else /* !_POSIX_SOURCE && BSIZE */
175 # define ST_NBLOCKS(statbuf) \
176 (S_ISREG ((statbuf).st_mode) \
177 || S_ISDIR ((statbuf).st_mode) \
178 ? st_blocks ((statbuf).st_size) : 0)
179 # endif /* !_POSIX_SOURCE && BSIZE */
180 #else /* HAVE_STRUCT_STAT_ST_BLOCKS */
181 /* Some systems, like Sequents, return st_blksize of 0 on pipes.
182 Also, when running `rsh hpux11-system cat any-file', cat would
183 determine that the output stream had an st_blksize of 2147421096.
184 Conversely st_blksize can be 2 GiB (or maybe even larger) with XFS
185 on 64-bit hosts. Somewhat arbitrarily, limit the `optimal' block
186 size to SIZE_MAX / 8 + 1. (Dividing SIZE_MAX by only 4 wouldn't
187 suffice, since "cat" sometimes multiplies the result by 4.) If
188 anyone knows of a system for which this limit is too small, please
189 report it as a bug in this code. */
190 # define ST_BLKSIZE(statbuf) ((0 < (statbuf).st_blksize \
191 && (statbuf).st_blksize <= SIZE_MAX / 8 + 1) \
192 ? (statbuf).st_blksize : DEV_BSIZE)
193 # if defined hpux || defined __hpux__ || defined __hpux
194 /* HP-UX counts st_blocks in 1024-byte units.
195 This loses when mixing HP-UX and BSD file systems with NFS. */
196 # define ST_NBLOCKSIZE 1024
197 # else /* !hpux */
198 # if defined _AIX && defined _I386
199 /* AIX PS/2 counts st_blocks in 4K units. */
200 # define ST_NBLOCKSIZE (4 * 1024)
201 # else /* not AIX PS/2 */
202 # if defined _CRAY
203 # define ST_NBLOCKS(statbuf) \
204 (S_ISREG ((statbuf).st_mode) \
205 || S_ISDIR ((statbuf).st_mode) \
206 ? (statbuf).st_blocks * ST_BLKSIZE(statbuf)/ST_NBLOCKSIZE : 0)
207 # endif /* _CRAY */
208 # endif /* not AIX PS/2 */
209 # endif /* !hpux */
210 #endif /* HAVE_STRUCT_STAT_ST_BLOCKS */
212 #ifndef ST_NBLOCKS
213 # define ST_NBLOCKS(statbuf) ((statbuf).st_blocks)
214 #endif
216 #ifndef ST_NBLOCKSIZE
217 # ifdef S_BLKSIZE
218 # define ST_NBLOCKSIZE S_BLKSIZE
219 # else
220 # define ST_NBLOCKSIZE 512
221 # endif
222 #endif
224 /* Redirection and wildcarding when done by the utility itself.
225 Generally a noop, but used in particular for native VMS. */
226 #ifndef initialize_main
227 # define initialize_main(ac, av)
228 #endif
230 #include "stat-macros.h"
232 #include "timespec.h"
234 #include <ctype.h>
236 #if ! (defined isblank || HAVE_DECL_ISBLANK)
237 # define isblank(c) ((c) == ' ' || (c) == '\t')
238 #endif
240 /* ISDIGIT differs from isdigit, as follows:
241 - Its arg may be any int or unsigned int; it need not be an unsigned char
242 or EOF.
243 - It's typically faster.
244 POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
245 isdigit unless it's important to use the locale's definition
246 of `digit' even when the host does not conform to POSIX. */
247 #define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
249 /* Convert a possibly-signed character to an unsigned character. This is
250 a bit safer than casting to unsigned char, since it catches some type
251 errors that the cast doesn't. */
252 static inline unsigned char to_uchar (char ch) { return ch; }
254 #include <locale.h>
256 /* Take care of NLS matters. */
258 #include "gettext.h"
259 #if ! ENABLE_NLS
260 # undef textdomain
261 # define textdomain(Domainname) /* empty */
262 # undef bindtextdomain
263 # define bindtextdomain(Domainname, Dirname) /* empty */
264 #endif
266 #define _(msgid) gettext (msgid)
267 #define N_(msgid) msgid
269 /* Return a value that pluralizes the same way that N does, in all
270 languages we know of. */
271 static inline unsigned long int
272 select_plural (uintmax_t n)
274 /* Reduce by a power of ten, but keep it away from zero. The
275 gettext manual says 1000000 should be safe. */
276 enum { PLURAL_REDUCER = 1000000 };
277 return (n <= ULONG_MAX ? n : n % PLURAL_REDUCER + PLURAL_REDUCER);
280 #define STREQ(a, b) (strcmp (a, b) == 0)
282 #if !HAVE_DECL_FREE
283 void free ();
284 #endif
286 #if !HAVE_DECL_MALLOC
287 char *malloc ();
288 #endif
290 #if !HAVE_DECL_MEMCHR
291 char *memchr ();
292 #endif
294 #if !HAVE_DECL_REALLOC
295 char *realloc ();
296 #endif
298 #if !HAVE_DECL_GETENV
299 char *getenv ();
300 #endif
302 #if !HAVE_DECL_LSEEK
303 off_t lseek ();
304 #endif
306 #if !HAVE_DECL_GETLOGIN
307 char *getlogin ();
308 #endif
310 #if !HAVE_DECL_TTYNAME
311 char *ttyname ();
312 #endif
314 #if !HAVE_DECL_GETEUID
315 uid_t geteuid ();
316 #endif
318 #if !HAVE_DECL_GETPWUID
319 struct passwd *getpwuid ();
320 #endif
322 #if !HAVE_DECL_GETGRGID
323 struct group *getgrgid ();
324 #endif
326 #if !HAVE_DECL_GETUID
327 uid_t getuid ();
328 #endif
330 #include "xalloc.h"
331 #include "verify.h"
333 /* This is simply a shorthand for the common case in which
334 the third argument to x2nrealloc would be `sizeof *(P)'.
335 Ensure that sizeof *(P) is *not* 1. In that case, it'd be
336 better to use X2REALLOC, although not strictly necessary. */
337 #define X2NREALLOC(P, PN) ((void) verify_true (sizeof *(P) != 1), \
338 x2nrealloc (P, PN, sizeof *(P)))
340 /* Using x2realloc (when appropriate) usually makes your code more
341 readable than using x2nrealloc, but it also makes it so your
342 code will malfunction if sizeof *(P) ever becomes 2 or greater.
343 So use this macro instead of using x2realloc directly. */
344 #define X2REALLOC(P, PN) ((void) verify_true (sizeof *(P) == 1), \
345 x2realloc (P, PN))
347 #include "unlocked-io.h"
348 #include "same-inode.h"
350 #include "dirname.h"
351 #include "openat.h"
353 static inline bool
354 dot_or_dotdot (char const *file_name)
356 if (file_name[0] == '.')
358 char sep = file_name[(file_name[1] == '.') + 1];
359 return (! sep || ISSLASH (sep));
361 else
362 return false;
365 /* A wrapper for readdir so that callers don't see entries for `.' or `..'. */
366 static inline struct dirent const *
367 readdir_ignoring_dot_and_dotdot (DIR *dirp)
369 while (1)
371 struct dirent const *dp = readdir (dirp);
372 if (dp == NULL || ! dot_or_dotdot (dp->d_name))
373 return dp;
377 /* Return true if DIR is determined to be an empty directory. */
378 static inline bool
379 is_empty_dir (int fd_cwd, char const *dir)
381 DIR *dirp;
382 struct dirent const *dp;
383 int saved_errno;
384 int fd = openat (fd_cwd, dir,
385 (O_RDONLY | O_DIRECTORY
386 | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK));
388 if (fd < 0)
389 return false;
391 dirp = fdopendir (fd);
392 if (dirp == NULL)
394 close (fd);
395 return false;
398 errno = 0;
399 dp = readdir_ignoring_dot_and_dotdot (dirp);
400 saved_errno = errno;
401 closedir (dirp);
402 if (dp != NULL)
403 return false;
404 return saved_errno == 0 ? true : false;
407 /* Factor out some of the common --help and --version processing code. */
409 /* These enum values cannot possibly conflict with the option values
410 ordinarily used by commands, including CHAR_MAX + 1, etc. Avoid
411 CHAR_MIN - 1, as it may equal -1, the getopt end-of-options value. */
412 enum
414 GETOPT_HELP_CHAR = (CHAR_MIN - 2),
415 GETOPT_VERSION_CHAR = (CHAR_MIN - 3)
418 #define GETOPT_HELP_OPTION_DECL \
419 "help", no_argument, NULL, GETOPT_HELP_CHAR
420 #define GETOPT_VERSION_OPTION_DECL \
421 "version", no_argument, NULL, GETOPT_VERSION_CHAR
422 #define GETOPT_SELINUX_CONTEXT_OPTION_DECL \
423 "context", required_argument, NULL, 'Z'
425 #define case_GETOPT_HELP_CHAR \
426 case GETOPT_HELP_CHAR: \
427 usage (EXIT_SUCCESS); \
428 break;
430 /* Program_name must be a literal string.
431 Usually it is just PROGRAM_NAME. */
432 #define USAGE_BUILTIN_WARNING \
433 _("\n" \
434 "NOTE: your shell may have its own version of %s, which usually supersedes\n" \
435 "the version described here. Please refer to your shell's documentation\n" \
436 "for details about the options it supports.\n")
438 #define HELP_OPTION_DESCRIPTION \
439 _(" --help display this help and exit\n")
440 #define VERSION_OPTION_DESCRIPTION \
441 _(" --version output version information and exit\n")
443 #include "closein.h"
444 #include "closeout.h"
446 #define emit_bug_reporting_address unused__emit_bug_reporting_address
447 #include "version-etc.h"
448 #undef emit_bug_reporting_address
450 #include "propername.h"
451 /* Define away proper_name (leaving proper_name_utf8, which affects far
452 fewer programs), since it's not worth the cost of adding ~17KB to
453 the x86_64 text size of every single program. This avoids a 40%
454 (almost ~2MB) increase in the on-disk space utilization for the set
455 of the 100 binaries. */
456 #define proper_name(x) (x)
458 #include "progname.h"
460 #define case_GETOPT_VERSION_CHAR(Program_name, Authors) \
461 case GETOPT_VERSION_CHAR: \
462 version_etc (stdout, Program_name, PACKAGE_NAME, Version, Authors, \
463 (char *) NULL); \
464 exit (EXIT_SUCCESS); \
465 break;
467 #ifndef MAX
468 # define MAX(a, b) ((a) > (b) ? (a) : (b))
469 #endif
471 #ifndef MIN
472 # define MIN(a,b) (((a) < (b)) ? (a) : (b))
473 #endif
475 #include "intprops.h"
477 #ifndef SSIZE_MAX
478 # define SSIZE_MAX TYPE_MAXIMUM (ssize_t)
479 #endif
481 #ifndef OFF_T_MIN
482 # define OFF_T_MIN TYPE_MINIMUM (off_t)
483 #endif
485 #ifndef OFF_T_MAX
486 # define OFF_T_MAX TYPE_MAXIMUM (off_t)
487 #endif
489 #ifndef UID_T_MAX
490 # define UID_T_MAX TYPE_MAXIMUM (uid_t)
491 #endif
493 #ifndef GID_T_MAX
494 # define GID_T_MAX TYPE_MAXIMUM (gid_t)
495 #endif
497 #ifndef PID_T_MAX
498 # define PID_T_MAX TYPE_MAXIMUM (pid_t)
499 #endif
501 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
502 #ifdef lint
503 # define IF_LINT(Code) Code
504 #else
505 # define IF_LINT(Code) /* empty */
506 #endif
508 /* With -Dlint, avoid warnings from gcc about code like mbstate_t m = {0,};
509 by wasting space on a static variable of the same type, that is thus
510 guaranteed to be initialized to 0, and use that on the RHS. */
511 #define DZA_CONCAT0(x,y) x ## y
512 #define DZA_CONCAT(x,y) DZA_CONCAT0 (x, y)
513 #ifdef lint
514 # define DECLARE_ZEROED_AGGREGATE(Type, Var) \
515 static Type DZA_CONCAT (s0_, __LINE__); Type Var = DZA_CONCAT (s0_, __LINE__)
516 #else
517 # define DECLARE_ZEROED_AGGREGATE(Type, Var) \
518 Type Var = { 0, }
519 #endif
521 #ifndef __attribute__
522 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8)
523 # define __attribute__(x) /* empty */
524 # endif
525 #endif
527 #ifndef ATTRIBUTE_NORETURN
528 # define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
529 #endif
531 #ifndef ATTRIBUTE_UNUSED
532 # define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
533 #endif
535 #if defined strdupa
536 # define ASSIGN_STRDUPA(DEST, S) \
537 do { DEST = strdupa (S); } while (0)
538 #else
539 # define ASSIGN_STRDUPA(DEST, S) \
540 do \
542 const char *s_ = (S); \
543 size_t len_ = strlen (s_) + 1; \
544 char *tmp_dest_ = alloca (len_); \
545 DEST = memcpy (tmp_dest_, s_, len_); \
547 while (0)
548 #endif
550 #ifndef EOVERFLOW
551 # define EOVERFLOW EINVAL
552 #endif
554 #if ! HAVE_SYNC
555 # define sync() /* empty */
556 #endif
558 /* Compute the greatest common divisor of U and V using Euclid's
559 algorithm. U and V must be nonzero. */
561 static inline size_t
562 gcd (size_t u, size_t v)
566 size_t t = u % v;
567 u = v;
568 v = t;
570 while (v);
572 return u;
575 /* Compute the least common multiple of U and V. U and V must be
576 nonzero. There is no overflow checking, so callers should not
577 specify outlandish sizes. */
579 static inline size_t
580 lcm (size_t u, size_t v)
582 return u * (v / gcd (u, v));
585 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
586 ALIGNMENT must be nonzero. The caller must arrange for ((char *)
587 PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
588 locations. */
590 static inline void *
591 ptr_align (void const *ptr, size_t alignment)
593 char const *p0 = ptr;
594 char const *p1 = p0 + alignment - 1;
595 return (void *) (p1 - (size_t) p1 % alignment);
598 /* If 10*Accum + Digit_val is larger than the maximum value for Type,
599 then don't update Accum and return false to indicate it would
600 overflow. Otherwise, set Accum to that new value and return true.
601 Verify at compile-time that Type is Accum's type, and that Type is
602 unsigned. Accum must be an object, so that we can take its
603 address. Accum and Digit_val may be evaluated multiple times.
605 The "Added check" below is not strictly required, but it causes GCC
606 to return a nonzero exit status instead of merely a warning
607 diagnostic, and that is more useful. */
609 #define DECIMAL_DIGIT_ACCUMULATE(Accum, Digit_val, Type) \
611 (void) (&(Accum) == (Type *) NULL), /* The type matches. */ \
612 (void) verify_true (! TYPE_SIGNED (Type)), /* The type is unsigned. */ \
613 (void) verify_true (sizeof (Accum) == sizeof (Type)), /* Added check. */ \
614 (((Type) -1 / 10 < (Accum) \
615 || (Type) ((Accum) * 10 + (Digit_val)) < (Accum)) \
616 ? false : (((Accum) = (Accum) * 10 + (Digit_val)), true)) \
619 #include "hard-locale.h"
620 static inline void
621 emit_bug_reporting_address (void)
623 printf (_("\nReport %s bugs to %s\n"), last_component (program_name),
624 PACKAGE_BUGREPORT);
625 /* FIXME 2010: use AC_PACKAGE_URL once we require autoconf-2.64 */
626 printf (_("%s home page: <http://www.gnu.org/software/%s/>\n"),
627 PACKAGE_NAME, PACKAGE);
628 fputs (_("General help using GNU software: <http://www.gnu.org/gethelp/>\n"),
629 stdout);
631 if (hard_locale (LC_MESSAGES))
633 /* TRANSLATORS: Replace LANG_CODE in this URL with your language code
634 <http://translationproject.org/team/LANG_CODE.html> to form one of
635 the URLs at http://translationproject.org/team/. Otherwise, replace
636 the entire URL with your translation team's email address. */
637 printf (_("Report %s translation bugs to "
638 "<http://translationproject.org/team/>\n"),
639 last_component (program_name));
643 #include "inttostr.h"
645 static inline char *
646 timetostr (time_t t, char *buf)
648 return (TYPE_SIGNED (time_t)
649 ? imaxtostr (t, buf)
650 : umaxtostr (t, buf));
653 static inline char *
654 bad_cast (char const *s)
656 return (char *) s;
659 /* As of Mar 2009, 32KiB is determined to be the minimium
660 blksize to best minimize system call overhead.
661 This can be tested with this script with the results
662 shown for a 1.7GHz pentium-m with 2GB of 400MHz DDR2 RAM:
664 for i in $(seq 0 10); do
665 size=$((8*1024**3)) #ensure this is big enough
666 bs=$((1024*2**$i))
667 printf "%7s=" $bs
668 dd bs=$bs if=/dev/zero of=/dev/null count=$(($size/$bs)) 2>&1 |
669 sed -n 's/.* \([0-9.]* [GM]B\/s\)/\1/p'
670 done
672 1024=734 MB/s
673 2048=1.3 GB/s
674 4096=2.4 GB/s
675 8192=3.5 GB/s
676 16384=3.9 GB/s
677 32768=5.2 GB/s
678 65536=5.3 GB/s
679 131072=5.5 GB/s
680 262144=5.7 GB/s
681 524288=5.7 GB/s
682 1048576=5.8 GB/s
684 Note that this is to minimize system call overhead.
685 Other values may be appropriate to minimize file system
686 or disk overhead. For example on my current GNU/Linux system
687 the readahead setting is 128KiB which was read using:
689 file="."
690 device=$(df -P --local "$file" | tail -n1 | cut -d' ' -f1)
691 echo $(( $(blockdev --getra $device) * 512 ))
693 However there isn't a portable way to get the above.
694 In the future we could use the above method if available
695 and default to io_blksize() if not.
697 enum { IO_BUFSIZE = 32*1024 };
698 static inline size_t
699 io_blksize (struct stat sb)
701 return MAX (IO_BUFSIZE, ST_BLKSIZE (sb));
704 void usage (int status) ATTRIBUTE_NORETURN;
706 #ifndef ARRAY_CARDINALITY
707 # define ARRAY_CARDINALITY(Array) (sizeof (Array) / sizeof *(Array))
708 #endif