maint: refactor copy to use is_nul()
[coreutils/ericb.git] / src / system.h
blob49cd08a3b0f14fc6e08bced016f2c0910ac4f372
1 /* system-dependent definitions for coreutils
2 Copyright (C) 1989-2012 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 this file _after_ system headers if possible. */
19 #include <alloca.h>
21 /* Include <sys/types.h> before this file.
22 Note this doesn't warn if we're included
23 before all system headers. */
25 #if 2 < __GLIBC__ || ( 2 == ___GLIBC__ && 2 <= __GLIBC_MINOR__ )
26 # if ! defined _SYS_TYPES_H
27 you must include <sys/types.h> before including this file
28 # endif
29 #endif
31 #include <sys/stat.h>
33 #if !defined HAVE_MKFIFO
34 # define mkfifo(name, mode) mknod (name, (mode) | S_IFIFO, 0)
35 #endif
37 #if HAVE_SYS_PARAM_H
38 # include <sys/param.h>
39 #endif
41 #include <unistd.h>
43 #include <limits.h>
44 #ifndef PATH_MAX
45 # define PATH_MAX 8192
46 #endif
48 #include "configmake.h"
50 #include <sys/time.h>
51 #include <time.h>
53 /* Since major is a function on SVR4, we can't use 'ifndef major'. */
54 #if MAJOR_IN_MKDEV
55 # include <sys/mkdev.h>
56 # define HAVE_MAJOR
57 #endif
58 #if MAJOR_IN_SYSMACROS
59 # include <sys/sysmacros.h>
60 # define HAVE_MAJOR
61 #endif
62 #ifdef major /* Might be defined in sys/types.h. */
63 # define HAVE_MAJOR
64 #endif
66 #ifndef HAVE_MAJOR
67 # define major(dev) (((dev) >> 8) & 0xff)
68 # define minor(dev) ((dev) & 0xff)
69 # define makedev(maj, min) (((maj) << 8) | (min))
70 #endif
71 #undef HAVE_MAJOR
73 #if ! defined makedev && defined mkdev
74 # define makedev(maj, min) mkdev (maj, min)
75 #endif
77 #include <string.h>
78 #include <errno.h>
80 /* Some systems don't define this; POSIX mentions it but says it is
81 obsolete. gnulib defines it, but only on native Windows systems,
82 and there only because MSVC 10 does. */
83 #ifndef ENODATA
84 # define ENODATA (-1)
85 #endif
87 #include <stdbool.h>
88 #include <stdlib.h>
89 #include "version.h"
91 /* Exit statuses for programs like 'env' that exec other programs. */
92 enum
94 EXIT_TIMEDOUT = 124, /* Time expired before child completed. */
95 EXIT_CANCELED = 125, /* Internal error prior to exec attempt. */
96 EXIT_CANNOT_INVOKE = 126, /* Program located, but not usable. */
97 EXIT_ENOENT = 127 /* Could not find program to exec. */
100 #include "exitfail.h"
102 /* Set exit_failure to STATUS if that's not the default already. */
103 static inline void
104 initialize_exit_failure (int status)
106 if (status != EXIT_FAILURE)
107 exit_failure = status;
110 #include <fcntl.h>
112 #include <dirent.h>
113 #ifndef _D_EXACT_NAMLEN
114 # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name)
115 #endif
117 enum
119 NOT_AN_INODE_NUMBER = 0
122 #ifdef D_INO_IN_DIRENT
123 # define D_INO(dp) (dp)->d_ino
124 #else
125 /* Some systems don't have inodes, so fake them to avoid lots of ifdefs. */
126 # define D_INO(dp) NOT_AN_INODE_NUMBER
127 #endif
129 /* include here for SIZE_MAX. */
130 #include <inttypes.h>
132 /* Redirection and wildcarding when done by the utility itself.
133 Generally a noop, but used in particular for native VMS. */
134 #ifndef initialize_main
135 # define initialize_main(ac, av)
136 #endif
138 #include "stat-macros.h"
140 #include "timespec.h"
142 #include <ctype.h>
144 /* ISDIGIT differs from isdigit, as follows:
145 - Its arg may be any int or unsigned int; it need not be an unsigned char
146 or EOF.
147 - It's typically faster.
148 POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
149 isdigit unless it's important to use the locale's definition
150 of 'digit' even when the host does not conform to POSIX. */
151 #define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
153 /* Convert a possibly-signed character to an unsigned character. This is
154 a bit safer than casting to unsigned char, since it catches some type
155 errors that the cast doesn't. */
156 static inline unsigned char to_uchar (char ch) { return ch; }
158 #include <locale.h>
160 /* Take care of NLS matters. */
162 #include "gettext.h"
163 #if ! ENABLE_NLS
164 # undef textdomain
165 # define textdomain(Domainname) /* empty */
166 # undef bindtextdomain
167 # define bindtextdomain(Domainname, Dirname) /* empty */
168 #endif
170 #define _(msgid) gettext (msgid)
171 #define N_(msgid) msgid
173 /* Return a value that pluralizes the same way that N does, in all
174 languages we know of. */
175 static inline unsigned long int
176 select_plural (uintmax_t n)
178 /* Reduce by a power of ten, but keep it away from zero. The
179 gettext manual says 1000000 should be safe. */
180 enum { PLURAL_REDUCER = 1000000 };
181 return (n <= ULONG_MAX ? n : n % PLURAL_REDUCER + PLURAL_REDUCER);
184 #define STREQ(a, b) (strcmp (a, b) == 0)
185 #define STREQ_LEN(a, b, n) (strncmp (a, b, n) == 0)
186 #define STRPREFIX(a, b) (strncmp(a, b, strlen (b)) == 0)
188 /* Just like strncmp, but the second argument must be a literal string
189 and you don't specify the length; that comes from the literal. */
190 #define STRNCMP_LIT(s, literal) \
191 strncmp (s, "" literal "", sizeof (literal) - 1)
193 #if !HAVE_DECL_GETLOGIN
194 char *getlogin ();
195 #endif
197 #if !HAVE_DECL_TTYNAME
198 char *ttyname ();
199 #endif
201 #if !HAVE_DECL_GETEUID
202 uid_t geteuid ();
203 #endif
205 #if !HAVE_DECL_GETPWUID
206 struct passwd *getpwuid ();
207 #endif
209 #if !HAVE_DECL_GETGRGID
210 struct group *getgrgid ();
211 #endif
213 /* Interix has replacements for getgr{gid,nam,ent}, that don't
214 query the domain controller for group members when not required.
215 This speeds up the calls tremendously (<1 ms vs. >3 s). */
216 /* To protect any system that could provide _nomembers functions
217 other than interix, check for HAVE_SETGROUPS, as interix is
218 one of the very few (the only?) platform that lacks it */
219 #if ! HAVE_SETGROUPS
220 # if HAVE_GETGRGID_NOMEMBERS
221 # define getgrgid(gid) getgrgid_nomembers(gid)
222 # endif
223 # if HAVE_GETGRNAM_NOMEMBERS
224 # define getgrnam(nam) getgrnam_nomembers(nam)
225 # endif
226 # if HAVE_GETGRENT_NOMEMBERS
227 # define getgrent() getgrent_nomembers()
228 # endif
229 #endif
231 #if !HAVE_DECL_GETUID
232 uid_t getuid ();
233 #endif
235 #include "xalloc.h"
236 #include "verify.h"
238 /* This is simply a shorthand for the common case in which
239 the third argument to x2nrealloc would be 'sizeof *(P)'.
240 Ensure that sizeof *(P) is *not* 1. In that case, it'd be
241 better to use X2REALLOC, although not strictly necessary. */
242 #define X2NREALLOC(P, PN) ((void) verify_true (sizeof *(P) != 1), \
243 x2nrealloc (P, PN, sizeof *(P)))
245 /* Using x2realloc (when appropriate) usually makes your code more
246 readable than using x2nrealloc, but it also makes it so your
247 code will malfunction if sizeof *(P) ever becomes 2 or greater.
248 So use this macro instead of using x2realloc directly. */
249 #define X2REALLOC(P, PN) ((void) verify_true (sizeof *(P) == 1), \
250 x2realloc (P, PN))
252 #include "unlocked-io.h"
253 #include "same-inode.h"
255 #include "dirname.h"
256 #include "openat.h"
258 static inline bool
259 dot_or_dotdot (char const *file_name)
261 if (file_name[0] == '.')
263 char sep = file_name[(file_name[1] == '.') + 1];
264 return (! sep || ISSLASH (sep));
266 else
267 return false;
270 /* A wrapper for readdir so that callers don't see entries for '.' or '..'. */
271 static inline struct dirent const *
272 readdir_ignoring_dot_and_dotdot (DIR *dirp)
274 while (1)
276 struct dirent const *dp = readdir (dirp);
277 if (dp == NULL || ! dot_or_dotdot (dp->d_name))
278 return dp;
282 /* Return true if DIR is determined to be an empty directory. */
283 static inline bool
284 is_empty_dir (int fd_cwd, char const *dir)
286 DIR *dirp;
287 struct dirent const *dp;
288 int saved_errno;
289 int fd = openat (fd_cwd, dir,
290 (O_RDONLY | O_DIRECTORY
291 | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK));
293 if (fd < 0)
294 return false;
296 dirp = fdopendir (fd);
297 if (dirp == NULL)
299 close (fd);
300 return false;
303 errno = 0;
304 dp = readdir_ignoring_dot_and_dotdot (dirp);
305 saved_errno = errno;
306 closedir (dirp);
307 if (dp != NULL)
308 return false;
309 return saved_errno == 0 ? true : false;
312 /* Factor out some of the common --help and --version processing code. */
314 /* These enum values cannot possibly conflict with the option values
315 ordinarily used by commands, including CHAR_MAX + 1, etc. Avoid
316 CHAR_MIN - 1, as it may equal -1, the getopt end-of-options value. */
317 enum
319 GETOPT_HELP_CHAR = (CHAR_MIN - 2),
320 GETOPT_VERSION_CHAR = (CHAR_MIN - 3)
323 #define GETOPT_HELP_OPTION_DECL \
324 "help", no_argument, NULL, GETOPT_HELP_CHAR
325 #define GETOPT_VERSION_OPTION_DECL \
326 "version", no_argument, NULL, GETOPT_VERSION_CHAR
327 #define GETOPT_SELINUX_CONTEXT_OPTION_DECL \
328 "context", required_argument, NULL, 'Z'
330 #define case_GETOPT_HELP_CHAR \
331 case GETOPT_HELP_CHAR: \
332 usage (EXIT_SUCCESS); \
333 break;
335 /* Program_name must be a literal string.
336 Usually it is just PROGRAM_NAME. */
337 #define USAGE_BUILTIN_WARNING \
338 _("\n" \
339 "NOTE: your shell may have its own version of %s, which usually supersedes\n" \
340 "the version described here. Please refer to your shell's documentation\n" \
341 "for details about the options it supports.\n")
343 #define HELP_OPTION_DESCRIPTION \
344 _(" --help display this help and exit\n")
345 #define VERSION_OPTION_DESCRIPTION \
346 _(" --version output version information and exit\n")
348 #include "closein.h"
349 #include "closeout.h"
351 #define emit_bug_reporting_address unused__emit_bug_reporting_address
352 #include "version-etc.h"
353 #undef emit_bug_reporting_address
355 #include "propername.h"
356 /* Define away proper_name (leaving proper_name_utf8, which affects far
357 fewer programs), since it's not worth the cost of adding ~17KB to
358 the x86_64 text size of every single program. This avoids a 40%
359 (almost ~2MB) increase in the on-disk space utilization for the set
360 of the 100 binaries. */
361 #define proper_name(x) (x)
363 #include "progname.h"
365 #define case_GETOPT_VERSION_CHAR(Program_name, Authors) \
366 case GETOPT_VERSION_CHAR: \
367 version_etc (stdout, Program_name, PACKAGE_NAME, Version, Authors, \
368 (char *) NULL); \
369 exit (EXIT_SUCCESS); \
370 break;
372 #ifndef MAX
373 # define MAX(a, b) ((a) > (b) ? (a) : (b))
374 #endif
376 #ifndef MIN
377 # define MIN(a,b) (((a) < (b)) ? (a) : (b))
378 #endif
380 #include "intprops.h"
382 #ifndef SSIZE_MAX
383 # define SSIZE_MAX TYPE_MAXIMUM (ssize_t)
384 #endif
386 #ifndef OFF_T_MIN
387 # define OFF_T_MIN TYPE_MINIMUM (off_t)
388 #endif
390 #ifndef OFF_T_MAX
391 # define OFF_T_MAX TYPE_MAXIMUM (off_t)
392 #endif
394 #ifndef UID_T_MAX
395 # define UID_T_MAX TYPE_MAXIMUM (uid_t)
396 #endif
398 #ifndef GID_T_MAX
399 # define GID_T_MAX TYPE_MAXIMUM (gid_t)
400 #endif
402 #ifndef PID_T_MAX
403 # define PID_T_MAX TYPE_MAXIMUM (pid_t)
404 #endif
406 /* Use this to suppress gcc's '...may be used before initialized' warnings. */
407 #ifdef lint
408 # define IF_LINT(Code) Code
409 #else
410 # define IF_LINT(Code) /* empty */
411 #endif
413 #ifndef __attribute__
414 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8)
415 # define __attribute__(x) /* empty */
416 # endif
417 #endif
419 #ifndef ATTRIBUTE_NORETURN
420 # define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
421 #endif
423 #ifndef ATTRIBUTE_UNUSED
424 # define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
425 #endif
427 /* The warn_unused_result attribute appeared first in gcc-3.4.0 */
428 #undef ATTRIBUTE_WARN_UNUSED_RESULT
429 #if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)
430 # define ATTRIBUTE_WARN_UNUSED_RESULT /* empty */
431 #else
432 # define ATTRIBUTE_WARN_UNUSED_RESULT __attribute__ ((__warn_unused_result__))
433 #endif
435 #if defined strdupa
436 # define ASSIGN_STRDUPA(DEST, S) \
437 do { DEST = strdupa (S); } while (0)
438 #else
439 # define ASSIGN_STRDUPA(DEST, S) \
440 do \
442 const char *s_ = (S); \
443 size_t len_ = strlen (s_) + 1; \
444 char *tmp_dest_ = alloca (len_); \
445 DEST = memcpy (tmp_dest_, s_, len_); \
447 while (0)
448 #endif
450 #if ! HAVE_SYNC
451 # define sync() /* empty */
452 #endif
454 /* Compute the greatest common divisor of U and V using Euclid's
455 algorithm. U and V must be nonzero. */
457 static inline size_t _GL_ATTRIBUTE_CONST
458 gcd (size_t u, size_t v)
462 size_t t = u % v;
463 u = v;
464 v = t;
466 while (v);
468 return u;
471 /* Compute the least common multiple of U and V. U and V must be
472 nonzero. There is no overflow checking, so callers should not
473 specify outlandish sizes. */
475 static inline size_t _GL_ATTRIBUTE_CONST
476 lcm (size_t u, size_t v)
478 return u * (v / gcd (u, v));
481 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
482 ALIGNMENT must be nonzero. The caller must arrange for ((char *)
483 PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
484 locations. */
486 static inline void *
487 ptr_align (void const *ptr, size_t alignment)
489 char const *p0 = ptr;
490 char const *p1 = p0 + alignment - 1;
491 return (void *) (p1 - (size_t) p1 % alignment);
494 /* Return whether the buffer consists entirely of NULs.
495 Note the word after the buffer must be non NUL. */
497 static inline bool _GL_ATTRIBUTE_PURE
498 is_nul (const char *buf, size_t bufsize)
500 typedef uintptr_t word;
502 /* Find first nonzero *word*, or the word with the sentinel. */
503 word *wp = (word *) buf;
504 while (*wp++ == 0)
505 continue;
507 /* Find the first nonzero *byte*, or the sentinel. */
508 char *cp = (char *) (wp - 1);
509 while (*cp++ == 0)
510 continue;
512 return cp > buf + bufsize;
515 /* If 10*Accum + Digit_val is larger than the maximum value for Type,
516 then don't update Accum and return false to indicate it would
517 overflow. Otherwise, set Accum to that new value and return true.
518 Verify at compile-time that Type is Accum's type, and that Type is
519 unsigned. Accum must be an object, so that we can take its
520 address. Accum and Digit_val may be evaluated multiple times.
522 The "Added check" below is not strictly required, but it causes GCC
523 to return a nonzero exit status instead of merely a warning
524 diagnostic, and that is more useful. */
526 #define DECIMAL_DIGIT_ACCUMULATE(Accum, Digit_val, Type) \
528 (void) (&(Accum) == (Type *) NULL), /* The type matches. */ \
529 (void) verify_true (! TYPE_SIGNED (Type)), /* The type is unsigned. */ \
530 (void) verify_true (sizeof (Accum) == sizeof (Type)), /* Added check. */ \
531 (((Type) -1 / 10 < (Accum) \
532 || (Type) ((Accum) * 10 + (Digit_val)) < (Accum)) \
533 ? false : (((Accum) = (Accum) * 10 + (Digit_val)), true)) \
536 static inline void
537 emit_size_note (void)
539 fputs (_("\n\
540 SIZE is an integer and optional unit (example: 10M is 10*1024*1024). Units\n\
541 are K, M, G, T, P, E, Z, Y (powers of 1024) or KB, MB, ... (powers of 1000).\n\
542 "), stdout);
545 static inline void
546 emit_blocksize_note (char const *program)
548 printf (_("\n\
549 Display values are in units of the first available SIZE from --block-size,\n\
550 and the %s_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables.\n\
551 Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set).\n\
552 "), program);
555 static inline void
556 emit_ancillary_info (void)
558 printf (_("\nReport %s bugs to %s\n"), last_component (program_name),
559 PACKAGE_BUGREPORT);
560 printf (_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
561 fputs (_("General help using GNU software: <http://www.gnu.org/gethelp/>\n"),
562 stdout);
563 /* Don't output this redundant message for English locales.
564 Note we still output for 'C' so that it gets included in the man page. */
565 const char *lc_messages = setlocale (LC_MESSAGES, NULL);
566 if (lc_messages && STRNCMP_LIT (lc_messages, "en_"))
568 /* TRANSLATORS: Replace LANG_CODE in this URL with your language code
569 <http://translationproject.org/team/LANG_CODE.html> to form one of
570 the URLs at http://translationproject.org/team/. Otherwise, replace
571 the entire URL with your translation team's email address. */
572 printf (_("Report %s translation bugs to "
573 "<http://translationproject.org/team/>\n"),
574 last_component (program_name));
576 printf (_("For complete documentation, run: "
577 "info coreutils '%s invocation'\n"), last_component (program_name));
580 static inline void
581 emit_try_help (void)
583 fprintf (stderr, _("Try '%s --help' for more information.\n"), program_name);
586 #include "inttostr.h"
588 static inline char *
589 timetostr (time_t t, char *buf)
591 return (TYPE_SIGNED (time_t)
592 ? imaxtostr (t, buf)
593 : umaxtostr (t, buf));
596 static inline char *
597 bad_cast (char const *s)
599 return (char *) s;
602 void usage (int status) ATTRIBUTE_NORETURN;
604 #define emit_cycle_warning(file_name) \
605 do \
607 error (0, 0, _("\
608 WARNING: Circular directory structure.\n\
609 This almost certainly means that you have a corrupted file system.\n\
610 NOTIFY YOUR SYSTEM MANAGER.\n\
611 The following directory is part of the cycle:\n %s\n"), \
612 quote (file_name)); \
614 while (0)
616 #ifndef ARRAY_CARDINALITY
617 # define ARRAY_CARDINALITY(Array) (sizeof (Array) / sizeof *(Array))
618 #endif