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