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