TODO: add an item for a chmod optimization
[platform/upstream/coreutils.git] / src / system.h
1 /* system-dependent definitions for coreutils
2    Copyright (C) 1989, 1991-2008 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>.  */
16
17 #include <alloca.h>
18
19 /* Include sys/types.h before this file.  */
20
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
26
27 #include <sys/stat.h>
28
29 #if !defined HAVE_MKFIFO
30 # define mkfifo(name, mode) mknod (name, (mode) | S_IFIFO, 0)
31 #endif
32
33 #if HAVE_SYS_PARAM_H
34 # include <sys/param.h>
35 #endif
36
37 #include <unistd.h>
38
39 #ifndef STDIN_FILENO
40 # define STDIN_FILENO 0
41 #endif
42
43 #ifndef STDOUT_FILENO
44 # define STDOUT_FILENO 1
45 #endif
46
47 #ifndef STDERR_FILENO
48 # define STDERR_FILENO 2
49 #endif
50
51
52 /* limits.h must come before pathmax.h because limits.h on some systems
53    undefs PATH_MAX, whereas pathmax.h sets PATH_MAX.  */
54 #include <limits.h>
55
56 #include "pathmax.h"
57
58 #include "configmake.h"
59
60 #if TIME_WITH_SYS_TIME
61 # include <sys/time.h>
62 # include <time.h>
63 #else
64 # if HAVE_SYS_TIME_H
65 #  include <sys/time.h>
66 # else
67 #  include <time.h>
68 # endif
69 #endif
70
71 /* Since major is a function on SVR4, we can't use `ifndef major'.  */
72 #if MAJOR_IN_MKDEV
73 # include <sys/mkdev.h>
74 # define HAVE_MAJOR
75 #endif
76 #if MAJOR_IN_SYSMACROS
77 # include <sys/sysmacros.h>
78 # define HAVE_MAJOR
79 #endif
80 #ifdef major                    /* Might be defined in sys/types.h.  */
81 # define HAVE_MAJOR
82 #endif
83
84 #ifndef HAVE_MAJOR
85 # define major(dev)  (((dev) >> 8) & 0xff)
86 # define minor(dev)  ((dev) & 0xff)
87 # define makedev(maj, min)  (((maj) << 8) | (min))
88 #endif
89 #undef HAVE_MAJOR
90
91 #if ! defined makedev && defined mkdev
92 # define makedev(maj, min)  mkdev (maj, min)
93 #endif
94
95 /* Don't use bcopy!  Use memmove if source and destination may overlap,
96    memcpy otherwise.  */
97
98 #include <string.h>
99
100 #include <errno.h>
101
102 /* Some systems don't define the following symbols.  */
103 #ifndef EDQUOT
104 # define EDQUOT (-1)
105 #endif
106 #ifndef EISDIR
107 # define EISDIR (-1)
108 #endif
109 #ifndef ENOSYS
110 # define ENOSYS (-1)
111 #endif
112 #ifndef ENODATA
113 # define ENODATA (-1)
114 #endif
115
116 #include <stdbool.h>
117 #include <stdlib.h>
118 #include "version.h"
119
120 /* Exit statuses for programs like 'env' that exec other programs.  */
121 enum
122 {
123   EXIT_CANNOT_INVOKE = 126,
124   EXIT_ENOENT = 127
125 };
126
127 #include "exitfail.h"
128
129 /* Set exit_failure to STATUS if that's not the default already.  */
130 static inline void
131 initialize_exit_failure (int status)
132 {
133   if (status != EXIT_FAILURE)
134     exit_failure = status;
135 }
136
137 #include <fcntl.h>
138
139 #ifndef F_OK
140 # define F_OK 0
141 # define X_OK 1
142 # define W_OK 2
143 # define R_OK 4
144 #endif
145
146 #include <dirent.h>
147 #ifndef _D_EXACT_NAMLEN
148 # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name)
149 #endif
150
151 enum
152 {
153   NOT_AN_INODE_NUMBER = 0
154 };
155
156 #ifdef D_INO_IN_DIRENT
157 # define D_INO(dp) (dp)->d_ino
158 #else
159 /* Some systems don't have inodes, so fake them to avoid lots of ifdefs.  */
160 # define D_INO(dp) NOT_AN_INODE_NUMBER
161 #endif
162
163 /* Get or fake the disk device blocksize.
164    Usually defined by sys/param.h (if at all).  */
165 #if !defined DEV_BSIZE && defined BSIZE
166 # define DEV_BSIZE BSIZE
167 #endif
168 #if !defined DEV_BSIZE && defined BBSIZE /* SGI */
169 # define DEV_BSIZE BBSIZE
170 #endif
171 #ifndef DEV_BSIZE
172 # define DEV_BSIZE 4096
173 #endif
174
175 /* Extract or fake data from a `struct stat'.
176    ST_BLKSIZE: Preferred I/O blocksize for the file, in bytes.
177    ST_NBLOCKS: Number of blocks in the file, including indirect blocks.
178    ST_NBLOCKSIZE: Size of blocks used when calculating ST_NBLOCKS.  */
179 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
180 # define ST_BLKSIZE(statbuf) DEV_BSIZE
181 # if defined _POSIX_SOURCE || !defined BSIZE /* fileblocks.c uses BSIZE.  */
182 #  define ST_NBLOCKS(statbuf) \
183   ((statbuf).st_size / ST_NBLOCKSIZE + ((statbuf).st_size % ST_NBLOCKSIZE != 0))
184 # else /* !_POSIX_SOURCE && BSIZE */
185 #  define ST_NBLOCKS(statbuf) \
186   (S_ISREG ((statbuf).st_mode) \
187    || S_ISDIR ((statbuf).st_mode) \
188    ? st_blocks ((statbuf).st_size) : 0)
189 # endif /* !_POSIX_SOURCE && BSIZE */
190 #else /* HAVE_STRUCT_STAT_ST_BLOCKS */
191 /* Some systems, like Sequents, return st_blksize of 0 on pipes.
192    Also, when running `rsh hpux11-system cat any-file', cat would
193    determine that the output stream had an st_blksize of 2147421096.
194    Conversely st_blksize can be 2 GiB (or maybe even larger) with XFS
195    on 64-bit hosts.  Somewhat arbitrarily, limit the `optimal' block
196    size to SIZE_MAX / 8 + 1.  (Dividing SIZE_MAX by only 4 wouldn't
197    suffice, since "cat" sometimes multiplies the result by 4.)  If
198    anyone knows of a system for which this limit is too small, please
199    report it as a bug in this code.  */
200 # define ST_BLKSIZE(statbuf) ((0 < (statbuf).st_blksize \
201                                && (statbuf).st_blksize <= SIZE_MAX / 8 + 1) \
202                               ? (statbuf).st_blksize : DEV_BSIZE)
203 # if defined hpux || defined __hpux__ || defined __hpux
204 /* HP-UX counts st_blocks in 1024-byte units.
205    This loses when mixing HP-UX and BSD file systems with NFS.  */
206 #  define ST_NBLOCKSIZE 1024
207 # else /* !hpux */
208 #  if defined _AIX && defined _I386
209 /* AIX PS/2 counts st_blocks in 4K units.  */
210 #   define ST_NBLOCKSIZE (4 * 1024)
211 #  else /* not AIX PS/2 */
212 #   if defined _CRAY
213 #    define ST_NBLOCKS(statbuf) \
214   (S_ISREG ((statbuf).st_mode) \
215    || S_ISDIR ((statbuf).st_mode) \
216    ? (statbuf).st_blocks * ST_BLKSIZE(statbuf)/ST_NBLOCKSIZE : 0)
217 #   endif /* _CRAY */
218 #  endif /* not AIX PS/2 */
219 # endif /* !hpux */
220 #endif /* HAVE_STRUCT_STAT_ST_BLOCKS */
221
222 #ifndef ST_NBLOCKS
223 # define ST_NBLOCKS(statbuf) ((statbuf).st_blocks)
224 #endif
225
226 #ifndef ST_NBLOCKSIZE
227 # ifdef S_BLKSIZE
228 #  define ST_NBLOCKSIZE S_BLKSIZE
229 # else
230 #  define ST_NBLOCKSIZE 512
231 # endif
232 #endif
233
234 /* Redirection and wildcarding when done by the utility itself.
235    Generally a noop, but used in particular for native VMS. */
236 #ifndef initialize_main
237 # define initialize_main(ac, av)
238 #endif
239
240 #include "stat-macros.h"
241
242 #include "timespec.h"
243
244 #include <inttypes.h>
245
246 #include <ctype.h>
247
248 #if ! (defined isblank || HAVE_DECL_ISBLANK)
249 # define isblank(c) ((c) == ' ' || (c) == '\t')
250 #endif
251
252 /* ISDIGIT differs from isdigit, as follows:
253    - Its arg may be any int or unsigned int; it need not be an unsigned char
254      or EOF.
255    - It's typically faster.
256    POSIX says that only '0' through '9' are digits.  Prefer ISDIGIT to
257    isdigit unless it's important to use the locale's definition
258    of `digit' even when the host does not conform to POSIX.  */
259 #define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
260
261 /* Convert a possibly-signed character to an unsigned character.  This is
262    a bit safer than casting to unsigned char, since it catches some type
263    errors that the cast doesn't.  */
264 static inline unsigned char to_uchar (char ch) { return ch; }
265
266 #include <locale.h>
267
268 /* Take care of NLS matters.  */
269
270 #include "gettext.h"
271 #if ! ENABLE_NLS
272 # undef textdomain
273 # define textdomain(Domainname) /* empty */
274 # undef bindtextdomain
275 # define bindtextdomain(Domainname, Dirname) /* empty */
276 #endif
277
278 #define _(msgid) gettext (msgid)
279 #define N_(msgid) msgid
280
281 /* Return a value that pluralizes the same way that N does, in all
282    languages we know of.  */
283 static inline unsigned long int
284 select_plural (uintmax_t n)
285 {
286   /* Reduce by a power of ten, but keep it away from zero.  The
287      gettext manual says 1000000 should be safe.  */
288   enum { PLURAL_REDUCER = 1000000 };
289   return (n <= ULONG_MAX ? n : n % PLURAL_REDUCER + PLURAL_REDUCER);
290 }
291
292 #define STREQ(a, b) (strcmp (a, b) == 0)
293
294 #if !HAVE_DECL_FREE
295 void free ();
296 #endif
297
298 #if !HAVE_DECL_MALLOC
299 char *malloc ();
300 #endif
301
302 #if !HAVE_DECL_MEMCHR
303 char *memchr ();
304 #endif
305
306 #if !HAVE_DECL_REALLOC
307 char *realloc ();
308 #endif
309
310 #if !HAVE_DECL_GETENV
311 char *getenv ();
312 #endif
313
314 #if !HAVE_DECL_LSEEK
315 off_t lseek ();
316 #endif
317
318 #if !HAVE_DECL_GETLOGIN
319 char *getlogin ();
320 #endif
321
322 #if !HAVE_DECL_TTYNAME
323 char *ttyname ();
324 #endif
325
326 #if !HAVE_DECL_GETEUID
327 uid_t geteuid ();
328 #endif
329
330 #if !HAVE_DECL_GETPWUID
331 struct passwd *getpwuid ();
332 #endif
333
334 #if !HAVE_DECL_GETGRGID
335 struct group *getgrgid ();
336 #endif
337
338 #if !HAVE_DECL_GETUID
339 uid_t getuid ();
340 #endif
341
342 #include "xalloc.h"
343 #include "verify.h"
344
345 /* This is simply a shorthand for the common case in which
346    the third argument to x2nrealloc would be `sizeof *(P)'.
347    Ensure that sizeof *(P) is *not* 1.  In that case, it'd be
348    better to use X2REALLOC, although not strictly necessary.  */
349 #define X2NREALLOC(P, PN) ((void) verify_true (sizeof *(P) != 1), \
350                            x2nrealloc (P, PN, sizeof *(P)))
351
352 /* Using x2realloc (when appropriate) usually makes your code more
353    readable than using x2nrealloc, but it also makes it so your
354    code will malfunction if sizeof *(P) ever becomes 2 or greater.
355    So use this macro instead of using x2realloc directly.  */
356 #define X2REALLOC(P, PN) ((void) verify_true (sizeof *(P) == 1), \
357                           x2realloc (P, PN))
358
359 #include "unlocked-io.h"
360 #include "same-inode.h"
361
362 #include "dirname.h"
363 #include "openat.h"
364
365 static inline bool
366 dot_or_dotdot (char const *file_name)
367 {
368   if (file_name[0] == '.')
369     {
370       char sep = file_name[(file_name[1] == '.') + 1];
371       return (! sep || ISSLASH (sep));
372     }
373   else
374     return false;
375 }
376
377 /* A wrapper for readdir so that callers don't see entries for `.' or `..'.  */
378 static inline struct dirent const *
379 readdir_ignoring_dot_and_dotdot (DIR *dirp)
380 {
381   while (1)
382     {
383       struct dirent const *dp = readdir (dirp);
384       if (dp == NULL || ! dot_or_dotdot (dp->d_name))
385         return dp;
386     }
387 }
388
389 /* Return true if DIR is determined to be an empty directory.  */
390 static inline bool
391 is_empty_dir (int fd_cwd, char const *dir)
392 {
393   DIR *dirp;
394   struct dirent const *dp;
395   int saved_errno;
396   int fd = openat (fd_cwd, dir,
397                    (O_RDONLY | O_DIRECTORY
398                     | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK));
399
400   if (fd < 0)
401     return false;
402
403   dirp = fdopendir (fd);
404   if (dirp == NULL)
405     {
406       close (fd);
407       return false;
408     }
409
410   errno = 0;
411   dp = readdir_ignoring_dot_and_dotdot (dirp);
412   saved_errno = errno;
413   closedir (dirp);
414   if (dp != NULL)
415     return false;
416   return saved_errno == 0 ? true : false;
417 }
418
419 /* Factor out some of the common --help and --version processing code.  */
420
421 /* These enum values cannot possibly conflict with the option values
422    ordinarily used by commands, including CHAR_MAX + 1, etc.  Avoid
423    CHAR_MIN - 1, as it may equal -1, the getopt end-of-options value.  */
424 enum
425 {
426   GETOPT_HELP_CHAR = (CHAR_MIN - 2),
427   GETOPT_VERSION_CHAR = (CHAR_MIN - 3)
428 };
429
430 #define GETOPT_HELP_OPTION_DECL \
431   "help", no_argument, NULL, GETOPT_HELP_CHAR
432 #define GETOPT_VERSION_OPTION_DECL \
433   "version", no_argument, NULL, GETOPT_VERSION_CHAR
434 #define GETOPT_SELINUX_CONTEXT_OPTION_DECL \
435   "context", required_argument, NULL, 'Z'
436
437 #define case_GETOPT_HELP_CHAR                   \
438   case GETOPT_HELP_CHAR:                        \
439     usage (EXIT_SUCCESS);                       \
440     break;
441
442 /* Program_name must be a literal string.
443    Usually it is just PROGRAM_NAME.  */
444 #define USAGE_BUILTIN_WARNING \
445   _("\n" \
446 "NOTE: your shell may have its own version of %s, which usually supersedes\n" \
447 "the version described here.  Please refer to your shell's documentation\n" \
448 "for details about the options it supports.\n")
449
450 #define HELP_OPTION_DESCRIPTION \
451   _("      --help     display this help and exit\n")
452 #define VERSION_OPTION_DESCRIPTION \
453   _("      --version  output version information and exit\n")
454
455 #include "closein.h"
456 #include "closeout.h"
457 #include "version-etc.h"
458 #include "propername.h"
459 /* Define away proper_name (leaving proper_name_utf8, which affects far
460    fewer programs), since it's not worth the cost of adding ~17KB to
461    the x86_64 text size of every single program.  This avoids a 40%
462    (almost ~2MB) increase in the on-disk space utilization for the set
463    of the 100 binaries. */
464 #define proper_name(x) (x)
465
466 #include "progname.h"
467
468 #define case_GETOPT_VERSION_CHAR(Program_name, Authors)                 \
469   case GETOPT_VERSION_CHAR:                                             \
470     version_etc (stdout, Program_name, PACKAGE_NAME, Version, Authors,  \
471                  (char *) NULL);                                        \
472     exit (EXIT_SUCCESS);                                                \
473     break;
474
475 #ifndef MAX
476 # define MAX(a, b) ((a) > (b) ? (a) : (b))
477 #endif
478
479 #ifndef MIN
480 # define MIN(a,b) (((a) < (b)) ? (a) : (b))
481 #endif
482
483 #include "intprops.h"
484
485 #ifndef SSIZE_MAX
486 # define SSIZE_MAX TYPE_MAXIMUM (ssize_t)
487 #endif
488
489 #ifndef OFF_T_MIN
490 # define OFF_T_MIN TYPE_MINIMUM (off_t)
491 #endif
492
493 #ifndef OFF_T_MAX
494 # define OFF_T_MAX TYPE_MAXIMUM (off_t)
495 #endif
496
497 #ifndef UID_T_MAX
498 # define UID_T_MAX TYPE_MAXIMUM (uid_t)
499 #endif
500
501 #ifndef GID_T_MAX
502 # define GID_T_MAX TYPE_MAXIMUM (gid_t)
503 #endif
504
505 #ifndef PID_T_MAX
506 # define PID_T_MAX TYPE_MAXIMUM (pid_t)
507 #endif
508
509 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
510 #ifdef lint
511 # define IF_LINT(Code) Code
512 #else
513 # define IF_LINT(Code) /* empty */
514 #endif
515
516 #ifndef __attribute__
517 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8)
518 #  define __attribute__(x) /* empty */
519 # endif
520 #endif
521
522 #ifndef ATTRIBUTE_NORETURN
523 # define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
524 #endif
525
526 #ifndef ATTRIBUTE_UNUSED
527 # define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
528 #endif
529
530 #if defined strdupa
531 # define ASSIGN_STRDUPA(DEST, S)                \
532   do { DEST = strdupa (S); } while (0)
533 #else
534 # define ASSIGN_STRDUPA(DEST, S)                \
535   do                                            \
536     {                                           \
537       const char *s_ = (S);                     \
538       size_t len_ = strlen (s_) + 1;            \
539       char *tmp_dest_ = alloca (len_);          \
540       DEST = memcpy (tmp_dest_, s_, len_);      \
541     }                                           \
542   while (0)
543 #endif
544
545 #ifndef EOVERFLOW
546 # define EOVERFLOW EINVAL
547 #endif
548
549 #if ! HAVE_SYNC
550 # define sync() /* empty */
551 #endif
552
553 /* Compute the greatest common divisor of U and V using Euclid's
554    algorithm.  U and V must be nonzero.  */
555
556 static inline size_t
557 gcd (size_t u, size_t v)
558 {
559   do
560     {
561       size_t t = u % v;
562       u = v;
563       v = t;
564     }
565   while (v);
566
567   return u;
568 }
569
570 /* Compute the least common multiple of U and V.  U and V must be
571    nonzero.  There is no overflow checking, so callers should not
572    specify outlandish sizes.  */
573
574 static inline size_t
575 lcm (size_t u, size_t v)
576 {
577   return u * (v / gcd (u, v));
578 }
579
580 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
581    ALIGNMENT must be nonzero.  The caller must arrange for ((char *)
582    PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
583    locations.  */
584
585 static inline void *
586 ptr_align (void const *ptr, size_t alignment)
587 {
588   char const *p0 = ptr;
589   char const *p1 = p0 + alignment - 1;
590   return (void *) (p1 - (size_t) p1 % alignment);
591 }
592
593 /* If 10*Accum + Digit_val is larger than the maximum value for Type,
594    then don't update Accum and return false to indicate it would
595    overflow.  Otherwise, set Accum to that new value and return true.
596    Verify at compile-time that Type is Accum's type, and that Type is
597    unsigned.  Accum must be an object, so that we can take its
598    address.  Accum and Digit_val may be evaluated multiple times.
599
600    The "Added check" below is not strictly required, but it causes GCC
601    to return a nonzero exit status instead of merely a warning
602    diagnostic, and that is more useful.  */
603
604 #define DECIMAL_DIGIT_ACCUMULATE(Accum, Digit_val, Type)                \
605   (                                                                     \
606    (void) (&(Accum) == (Type *) NULL),  /* The type matches.  */        \
607    (void) verify_true (! TYPE_SIGNED (Type)), /* The type is unsigned.  */ \
608    (void) verify_true (sizeof (Accum) == sizeof (Type)), /* Added check.  */ \
609    (((Type) -1 / 10 < (Accum)                                           \
610      || (Type) ((Accum) * 10 + (Digit_val)) < (Accum))                  \
611     ? false : (((Accum) = (Accum) * 10 + (Digit_val)), true))           \
612   )
613
614 static inline void
615 emit_bug_reporting_address (void)
616 {
617   /* TRANSLATORS: The placeholder indicates the bug-reporting address
618      for this package.  Please add _another line_ saying
619      "Report translation bugs to <...>\n" with the address for translation
620      bugs (typically your translation team's web or email address).  */
621   printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
622 }
623
624 #include "inttostr.h"
625
626 static inline char *
627 timetostr (time_t t, char *buf)
628 {
629   return (TYPE_SIGNED (time_t)
630           ? imaxtostr (t, buf)
631           : umaxtostr (t, buf));
632 }