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