1 /* system-dependent definitions for coreutils
2 Copyright (C) 1989-2024 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 <https://www.gnu.org/licenses/>. */
17 /* Include this file _after_ system headers if possible. */
19 #include <attribute.h>
25 /* Commonly used file permission combination. */
26 #define MODE_RW_UGO (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
29 # include <sys/param.h>
38 # define PATH_MAX 8192
41 #include "configmake.h"
46 /* Since major is a function on SVR4, we can't use 'ifndef major'. */
48 # include <sys/mkdev.h>
51 #if MAJOR_IN_SYSMACROS
52 # include <sys/sysmacros.h>
55 #ifdef major /* Might be defined in sys/types.h. */
60 # define major(dev) (((dev) >> 8) & 0xff)
61 # define minor(dev) ((dev) & 0xff)
62 # define makedev(maj, min) (((maj) << 8) | (min))
66 #if ! defined makedev && defined mkdev
67 # define makedev(maj, min) mkdev (maj, min)
70 #include <stdckdint.h>
75 /* Some systems don't define this; POSIX mentions it but says it is
76 obsolete. gnulib defines it, but only on native Windows systems,
77 and there only because MSVC 10 does. */
85 /* Exit statuses for programs like 'env' that exec other programs. */
88 EXIT_TIMEDOUT
= 124, /* Time expired before child completed. */
89 EXIT_CANCELED
= 125, /* Internal error prior to exec attempt. */
90 EXIT_CANNOT_INVOKE
= 126, /* Program located, but not usable. */
91 EXIT_ENOENT
= 127 /* Could not find program to exec. */
96 /* Set exit_failure to STATUS if that's not the default already. */
98 initialize_exit_failure (int status
)
100 if (status
!= EXIT_FAILURE
)
101 exit_failure
= status
;
106 enum { O_PATHSEARCH
= O_PATH
};
108 enum { O_PATHSEARCH
= O_SEARCH
};
112 #ifndef _D_EXACT_NAMLEN
113 # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name)
118 NOT_AN_INODE_NUMBER
= 0
121 #ifdef D_INO_IN_DIRENT
122 # define D_INO(dp) (dp)->d_ino
124 /* Some systems don't have inodes, so fake them to avoid lots of ifdefs. */
125 # define D_INO(dp) NOT_AN_INODE_NUMBER
128 /* include here for SIZE_MAX. */
129 #include <inttypes.h>
131 /* Redirection and wildcarding when done by the utility itself.
132 Generally a noop, but used in particular for OS/2. */
133 #ifndef initialize_main
135 # define initialize_main(ac, av)
137 # define initialize_main(ac, av) \
138 do { _wildcard (ac, av); _response (ac, av); } while (0)
142 #include "stat-macros.h"
144 #include "timespec.h"
146 /* ISDIGIT differs from isdigit, as follows:
147 - Its arg may be any int or unsigned int; it need not be an unsigned char
149 - It's typically faster.
150 POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
151 isdigit unless it's important to use the locale's definition
152 of 'digit' even when the host does not conform to POSIX. */
153 #define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
155 /* Convert a possibly-signed character to an unsigned character. This is
156 a bit safer than casting to unsigned char, since it catches some type
157 errors that the cast doesn't. */
158 static inline unsigned char to_uchar (char ch
) { return ch
; }
162 /* Take care of NLS matters. */
167 # define textdomain(Domainname) /* empty */
168 # undef bindtextdomain
169 # define bindtextdomain(Domainname, Dirname) /* empty */
172 #define _(msgid) gettext (msgid)
173 #define N_(msgid) msgid
175 /* Return a value that pluralizes the same way that N does, in all
176 languages we know of. */
177 static inline unsigned long int
178 select_plural (uintmax_t n
)
180 /* Reduce by a power of ten, but keep it away from zero. The
181 gettext manual says 1000000 should be safe. */
182 enum { PLURAL_REDUCER
= 1000000 };
183 return (n
<= ULONG_MAX
? n
: n
% PLURAL_REDUCER
+ PLURAL_REDUCER
);
186 #define STREQ(a, b) (strcmp (a, b) == 0)
187 #define STREQ_LEN(a, b, n) (strncmp (a, b, n) == 0) /* n==-1 means unbounded */
188 #define STRPREFIX(a, b) (strncmp (a, b, strlen (b)) == 0)
190 /* Just like strncmp, but the second argument must be a literal string
191 and you don't specify the length; that comes from the literal. */
192 #define STRNCMP_LIT(s, lit) strncmp (s, "" lit "", sizeof (lit) - 1)
194 #if !HAVE_DECL_GETLOGIN
195 char *getlogin (void);
198 #if !HAVE_DECL_TTYNAME
202 #if !HAVE_DECL_GETEUID
203 uid_t
geteuid (void);
206 #if !HAVE_DECL_GETPWUID
207 struct passwd
*getpwuid (uid_t
);
210 #if !HAVE_DECL_GETGRGID
211 struct group
*getgrgid (gid_t
);
214 /* Interix has replacements for getgr{gid,nam,ent}, that don't
215 query the domain controller for group members when not required.
216 This speeds up the calls tremendously (<1 ms vs. >3 s). */
217 /* To protect any system that could provide _nomembers functions
218 other than interix, check for HAVE_SETGROUPS, as interix is
219 one of the very few (the only?) platform that lacks it */
221 # if HAVE_GETGRGID_NOMEMBERS
222 # define getgrgid(gid) getgrgid_nomembers(gid)
224 # if HAVE_GETGRNAM_NOMEMBERS
225 # define getgrnam(nam) getgrnam_nomembers(nam)
227 # if HAVE_GETGRENT_NOMEMBERS
228 # define getgrent() getgrent_nomembers()
232 #if !HAVE_DECL_GETUID
239 #include "unlocked-io.h"
240 #include "same-inode.h"
246 dot_or_dotdot (char const *file_name
)
248 if (file_name
[0] == '.')
250 char sep
= file_name
[(file_name
[1] == '.') + 1];
251 return (! sep
|| ISSLASH (sep
));
257 /* A wrapper for readdir so that callers don't see entries for '.' or '..'. */
258 static inline struct dirent
const *
259 readdir_ignoring_dot_and_dotdot (DIR *dirp
)
263 struct dirent
const *dp
= readdir (dirp
);
264 if (dp
== nullptr || ! dot_or_dotdot (dp
->d_name
))
269 /* Return -1 if DIR is an empty directory,
270 0 if DIR is a nonempty directory,
271 and a positive error number if there was trouble determining
272 whether DIR is an empty or nonempty directory. */
279 directory_status (int fd_cwd
, char const *dir
)
284 int fd
= openat (fd_cwd
, dir
,
285 (O_RDONLY
| O_DIRECTORY
286 | O_NOCTTY
| O_NOFOLLOW
| O_NONBLOCK
));
291 dirp
= fdopendir (fd
);
300 no_direntries
= !readdir_ignoring_dot_and_dotdot (dirp
);
303 return no_direntries
&& saved_errno
== 0 ? DS_EMPTY
: saved_errno
;
306 /* Factor out some of the common --help and --version processing code. */
308 /* These enum values cannot possibly conflict with the option values
309 ordinarily used by commands, including CHAR_MAX + 1, etc. Avoid
310 CHAR_MIN - 1, as it may equal -1, the getopt end-of-options value. */
313 GETOPT_HELP_CHAR
= (CHAR_MIN
- 2),
314 GETOPT_VERSION_CHAR
= (CHAR_MIN
- 3)
317 #define GETOPT_HELP_OPTION_DECL \
318 "help", no_argument, nullptr, GETOPT_HELP_CHAR
319 #define GETOPT_VERSION_OPTION_DECL \
320 "version", no_argument, nullptr, GETOPT_VERSION_CHAR
321 #define GETOPT_SELINUX_CONTEXT_OPTION_DECL \
322 "context", optional_argument, nullptr, 'Z'
324 #define case_GETOPT_HELP_CHAR \
325 case GETOPT_HELP_CHAR: \
326 usage (EXIT_SUCCESS); \
329 /* Program_name must be a literal string.
330 Usually it is just PROGRAM_NAME. */
331 #define USAGE_BUILTIN_WARNING \
333 "Your shell may have its own version of %s, which usually supersedes\n" \
334 "the version described here. Please refer to your shell's documentation\n" \
335 "for details about the options it supports.\n")
337 #define HELP_OPTION_DESCRIPTION \
338 _(" --help display this help and exit\n")
339 #define VERSION_OPTION_DESCRIPTION \
340 _(" --version output version information and exit\n")
343 #include "closeout.h"
345 #define emit_bug_reporting_address unused__emit_bug_reporting_address
346 #include "version-etc.h"
347 #undef emit_bug_reporting_address
349 #include "propername.h"
350 /* Define away proper_name, since it's not worth the cost of adding ~17KB to
351 the x86_64 text size of every single program. This avoids a 40%
352 (almost ~2MB) increase in the file system space utilization for the set
353 of the 100 binaries. */
354 #define proper_name(x) proper_name_lite (x, x)
356 #include "progname.h"
358 #define case_GETOPT_VERSION_CHAR(Program_name, Authors) \
359 case GETOPT_VERSION_CHAR: \
360 version_etc (stdout, Program_name, PACKAGE_NAME, Version, Authors, \
362 exit (EXIT_SUCCESS); \
366 #include "intprops.h"
369 # define SSIZE_MAX TYPE_MAXIMUM (ssize_t)
373 # define OFF_T_MIN TYPE_MINIMUM (off_t)
377 # define OFF_T_MAX TYPE_MAXIMUM (off_t)
381 # define UID_T_MAX TYPE_MAXIMUM (uid_t)
385 # define GID_T_MAX TYPE_MAXIMUM (gid_t)
389 # define PID_T_MAX TYPE_MAXIMUM (pid_t)
392 /* Use this to suppress gcc warnings. */
394 # define IF_LINT(Code) Code
396 # define IF_LINT(Code) /* empty */
399 /* main_exit should be called only from the main function. It is
400 equivalent to 'exit'. When checking for lint it calls 'exit', to
401 pacify gcc -fsanitize=lint which would otherwise have false alarms
402 for pointers in the main function's activation record. Otherwise
403 it simply returns from 'main'; this used to be what gcc's static
404 checking preferred and may yet be again. */
406 # define main_exit(status) exit (status)
408 # define main_exit(status) return status
412 # define LIKELY(cond) __builtin_expect ((cond), 1)
413 # define UNLIKELY(cond) __builtin_expect ((cond), 0)
415 # define LIKELY(cond) (cond)
416 # define UNLIKELY(cond) (cond)
421 # define ASSIGN_STRDUPA(DEST, S) \
422 do { DEST = strdupa (S); } while (0)
424 # define ASSIGN_STRDUPA(DEST, S) \
427 char const *s_ = (S); \
428 size_t len_ = strlen (s_) + 1; \
429 char *tmp_dest_ = alloca (len_); \
430 DEST = memcpy (tmp_dest_, s_, len_); \
436 # define sync() /* empty */
439 /* Compute the greatest common divisor of U and V using Euclid's
440 algorithm. U and V must be nonzero. */
444 gcd (size_t u
, size_t v
)
457 /* Compute the least common multiple of U and V. U and V must be
458 nonzero. There is no overflow checking, so callers should not
459 specify outlandish sizes. */
463 lcm (size_t u
, size_t v
)
465 return u
* (v
/ gcd (u
, v
));
468 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
469 ALIGNMENT must be nonzero. The caller must arrange for ((char *)
470 PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
474 ptr_align (void const *ptr
, size_t alignment
)
476 char const *p0
= ptr
;
477 char const *p1
= p0
+ alignment
- 1;
478 return (void *) (p1
- (size_t) p1
% alignment
);
481 /* Return whether the buffer consists entirely of NULs.
482 Based on memeqzero in CCAN by Rusty Russell under CC0 (Public domain). */
486 is_nul (void const *buf
, size_t length
)
488 const unsigned char *p
= buf
;
489 /* Using possibly unaligned access for the first 16 bytes
490 saves about 30-40 cycles, though it is strictly undefined behavior
491 and so would need __attribute__ ((__no_sanitize_undefined__))
492 to avoid -fsanitize=undefined warnings.
493 Considering coreutils is mainly concerned with relatively
494 large buffers, we'll just use the defined behavior. */
495 #if 0 && (_STRING_ARCH_unaligned || _STRING_INLINE_unaligned)
504 /* Check len bytes not aligned on a word. */
505 while (UNLIKELY (length
& (sizeof word
- 1)))
515 /* Check up to 16 bytes a word at a time. */
518 memcpy (&word
, p
, sizeof word
);
522 length
-= sizeof word
;
525 if (UNLIKELY (length
& 15) == 0)
529 /* Now we know first 16 bytes are NUL, memcmp with self. */
530 return memcmp (buf
, p
, length
) == 0;
533 /* Set Accum = 10*Accum + Digit_val and return true, where Accum is an
534 integer object and Digit_val an integer expression. However, if
535 the result overflows, set Accum to an unspecified value and return
536 false. Accum and Digit_val may be evaluated multiple times. */
538 #define DECIMAL_DIGIT_ACCUMULATE(Accum, Digit_val) \
539 (!ckd_mul (&(Accum), Accum, 10) && !ckd_add (&(Accum), Accum, Digit_val))
542 emit_stdin_note (void)
545 With no FILE, or when FILE is -, read standard input.\n\
549 emit_mandatory_arg_note (void)
552 Mandatory arguments to long options are mandatory for short options too.\n\
557 emit_size_note (void)
560 The SIZE argument is an integer and optional unit (example: 10K is 10*1024).\n\
561 Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000).\n\
562 Binary prefixes can be used, too: KiB=K, MiB=M, and so on.\n\
567 emit_blocksize_note (char const *program
)
570 Display values are in units of the first available SIZE from --block-size,\n\
571 and the %s_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables.\n\
572 Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set).\n\
577 emit_update_parameters_note (void)
581 UPDATE controls which existing files in the destination are replaced.\n\
582 'all' is the default operation when an --update option is not specified,\n\
583 and results in all existing files in the destination being replaced.\n\
584 'none' is like the --no-clobber option, in that no files in the\n\
585 destination are replaced, and skipped files do not induce a failure.\n\
586 'none-fail' also ensures no files are replaced in the destination,\n\
587 but any skipped files are diagnosed and induce a failure.\n\
588 'older' is the default operation when --update is specified, and results\n\
589 in files being replaced if they're older than the corresponding source file.\n\
594 emit_backup_suffix_note (void)
598 The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
599 The version control method may be selected via the --backup option or through\n\
600 the VERSION_CONTROL environment variable. Here are the values:\n\
604 none, off never make backups (even if --backup is given)\n\
605 numbered, t make numbered backups\n\
606 existing, nil numbered if numbered backups exist, simple otherwise\n\
607 simple, never always make simple backups\n\
612 emit_symlink_recurse_options (char const *default_opt
)
616 The following options modify how a hierarchy is traversed when the -R\n\
617 option is also specified. If more than one is specified, only the final\n\
618 one takes effect. %s is the default.\n\
620 -H if a command line argument is a symbolic link\n\
621 to a directory, traverse it\n\
622 -L traverse every symbolic link to a directory\n\
624 -P do not traverse any symbolic links\n\
630 emit_exec_status (char const *program
)
634 125 if the %s command itself fails\n\
635 126 if COMMAND is found but cannot be invoked\n\
636 127 if COMMAND cannot be found\n\
637 - the exit status of COMMAND otherwise\n\
642 emit_ancillary_info (char const *program
)
644 struct infomap
{ char const *program
; char const *node
; } const infomap
[] = {
645 { "[", "test invocation" },
646 { "coreutils", "Multi-call invocation" },
647 { "sha224sum", "sha2 utilities" },
648 { "sha256sum", "sha2 utilities" },
649 { "sha384sum", "sha2 utilities" },
650 { "sha512sum", "sha2 utilities" },
654 char const *node
= program
;
655 struct infomap
const *map_prog
= infomap
;
657 while (map_prog
->program
&& ! STREQ (program
, map_prog
->program
))
661 node
= map_prog
->node
;
663 printf (_("\n%s online help: <%s>\n"), PACKAGE_NAME
, PACKAGE_URL
);
665 /* Don't output this redundant message for English locales.
666 Note we still output for 'C' so that it gets included in the man page. */
667 char const *lc_messages
= setlocale (LC_MESSAGES
, nullptr);
668 if (lc_messages
&& STRNCMP_LIT (lc_messages
, "en_"))
670 /* TRANSLATORS: Replace LANG_CODE in this URL with your language code
671 <https://translationproject.org/team/LANG_CODE.html> to form one of
672 the URLs at https://translationproject.org/team/. Otherwise, replace
673 the entire URL with your translation team's email address. */
674 fputs (_("Report any translation bugs to "
675 "<https://translationproject.org/team/>\n"), stdout
);
677 /* .htaccess on the coreutils web site maps programs to the appropriate page,
678 however we explicitly handle "[" -> "test" here as the "[" is not
679 recognized as part of a URL by default in terminals. */
680 char const *url_program
= STREQ (program
, "[") ? "test" : program
;
681 printf (_("Full documentation <%s%s>\n"),
682 PACKAGE_URL
, url_program
);
683 printf (_("or available locally via: info '(coreutils) %s%s'\n"),
684 node
, node
== program
? " invocation" : "");
687 /* Use a macro rather than an inline function, as this references
688 the global program_name, which causes dynamic linking issues
689 in libstdbuf.so on some systems where unused functions
690 are not removed by the linker. */
691 #define emit_try_help() \
694 fprintf (stderr, _("Try '%s --help' for more information.\n"), \
699 #include "inttostr.h"
702 timetostr (time_t t
, char *buf
)
704 return (TYPE_SIGNED (time_t)
706 : umaxtostr (t
, buf
));
710 bad_cast (char const *s
)
715 /* Return a boolean indicating whether SB->st_size is defined. */
717 usable_st_size (struct stat
const *sb
)
719 return (S_ISREG (sb
->st_mode
) || S_ISLNK (sb
->st_mode
)
720 || S_TYPEISSHM (sb
) || S_TYPEISTMO (sb
));
723 _Noreturn
void usage (int status
);
727 /* Like error(0, 0, ...), but without an implicit newline.
728 Also a noop unless the global DEV_DEBUG is set. */
729 #define devmsg(...) \
733 fprintf (stderr, __VA_ARGS__); \
737 #define emit_cycle_warning(file_name) \
741 WARNING: Circular directory structure.\n\
742 This almost certainly means that you have a corrupted file system.\n\
743 NOTIFY YOUR SYSTEM MANAGER.\n\
744 The following directory is part of the cycle:\n %s\n"), \
745 quotef (file_name)); \
749 /* exit with a _single_ "write error" diagnostic. */
754 int saved_errno
= errno
;
755 fflush (stdout
); /* Last attempt to write any buffered data. */
756 fpurge (stdout
); /* Ensure nothing buffered that might induce an error. */
757 clearerr (stdout
); /* Avoid extraneous diagnostic from close_stdout. */
758 error (EXIT_FAILURE
, saved_errno
, _("write error"));
761 /* Like stpncpy, but do ensure that the result is NUL-terminated,
762 and do not NUL-pad out to LEN. I.e., when strnlen (src, len) == len,
763 this function writes a NUL byte into dest[len]. Thus, the length
764 of the destination buffer must be at least LEN + 1.
765 The DEST and SRC buffers must not overlap. */
767 stzncpy (char *restrict dest
, char const *restrict src
, size_t len
)
770 for (i
= 0; i
< len
&& *src
; i
++)
776 #ifndef ARRAY_CARDINALITY
777 # define ARRAY_CARDINALITY(Array) (sizeof (Array) / sizeof *(Array))
780 /* Return true if ERR is ENOTSUP or EOPNOTSUPP, otherwise false.
781 This wrapper function avoids the redundant 'or'd comparison on
782 systems like Linux for which they have the same value. It also
783 avoids the gcc warning to that effect. */
787 return err
== EOPNOTSUPP
|| (ENOTSUP
!= EOPNOTSUPP
&& err
== ENOTSUP
);
791 /* How coreutils quotes filenames, to minimize use of outer quotes,
792 but also provide better support for copy and paste when used. */
793 #include "quotearg.h"
795 /* Use these to shell quote only when necessary,
796 when the quoted item is already delimited with colons. */
797 #define quotef(arg) \
798 quotearg_n_style_colon (0, shell_escape_quoting_style, arg)
799 #define quotef_n(n, arg) \
800 quotearg_n_style_colon (n, shell_escape_quoting_style, arg)
802 /* Use these when there are spaces around the file name,
803 in the error message. */
804 #define quoteaf(arg) \
805 quotearg_style (shell_escape_always_quoting_style, arg)
806 #define quoteaf_n(n, arg) \
807 quotearg_n_style (n, shell_escape_always_quoting_style, arg)