1 /* pred.c -- execute the expression tree.
2 Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, 2003,
3 2004, 2005, 2006, 2007, 2008, 2009,
4 2010 Free Software Foundation, Inc.
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
28 #include <sys/types.h>
36 #include <unistd.h> /* for unlinkat() */
41 #include "printquoted.h"
45 #include "stat-time.h"
46 #include "dircallback.h"
50 #include "areadlink.h"
54 #include <selinux/selinux.h>
58 # define _(Text) gettext (Text)
63 # define N_(String) gettext_noop (String)
65 /* See locate.c for explanation as to why not use (String) */
66 # define N_(String) String
69 #if !defined(SIGCHLD) && defined(SIGCLD)
70 #define SIGCHLD SIGCLD
78 # define NAMLEN(dirent) strlen((dirent)->d_name)
80 # define dirent direct
81 # define NAMLEN(dirent) (dirent)->d_namlen
83 # include <sys/ndir.h>
94 /* Fake a return value. */
95 #define CLOSEDIR(d) (closedir (d), 0)
97 #define CLOSEDIR(d) closedir (d)
103 /* Get or fake the disk device blocksize.
104 Usually defined by sys/param.h (if at all). */
107 # define DEV_BSIZE BSIZE
109 # define DEV_BSIZE 4096
111 #endif /* !DEV_BSIZE */
113 /* Extract or fake data from a `struct stat'.
114 ST_BLKSIZE: Preferred I/O blocksize for the file, in bytes.
115 ST_NBLOCKS: Number of blocks in the file, including indirect blocks.
116 ST_NBLOCKSIZE: Size of blocks used when calculating ST_NBLOCKS. */
117 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
118 # define ST_BLKSIZE(statbuf) DEV_BSIZE
119 # if defined _POSIX_SOURCE || !defined BSIZE /* fileblocks.c uses BSIZE. */
120 # define ST_NBLOCKS(statbuf) \
121 (S_ISREG ((statbuf).st_mode) \
122 || S_ISDIR ((statbuf).st_mode) \
123 ? (statbuf).st_size / ST_NBLOCKSIZE + ((statbuf).st_size % ST_NBLOCKSIZE != 0) : 0)
124 # else /* !_POSIX_SOURCE && BSIZE */
125 # define ST_NBLOCKS(statbuf) \
126 (S_ISREG ((statbuf).st_mode) \
127 || S_ISDIR ((statbuf).st_mode) \
128 ? st_blocks ((statbuf).st_size) : 0)
129 # endif /* !_POSIX_SOURCE && BSIZE */
130 #else /* HAVE_STRUCT_STAT_ST_BLOCKS */
131 /* Some systems, like Sequents, return st_blksize of 0 on pipes. */
132 # define ST_BLKSIZE(statbuf) ((statbuf).st_blksize > 0 \
133 ? (statbuf).st_blksize : DEV_BSIZE)
134 # if defined hpux || defined __hpux__ || defined __hpux
135 /* HP-UX counts st_blocks in 1024-byte units.
136 This loses when mixing HP-UX and BSD file systems with NFS. */
137 # define ST_NBLOCKSIZE 1024
139 # if defined _AIX && defined _I386
140 /* AIX PS/2 counts st_blocks in 4K units. */
141 # define ST_NBLOCKSIZE (4 * 1024)
142 # else /* not AIX PS/2 */
144 # define ST_NBLOCKS(statbuf) \
145 (S_ISREG ((statbuf).st_mode) \
146 || S_ISDIR ((statbuf).st_mode) \
147 ? (statbuf).st_blocks * ST_BLKSIZE(statbuf)/ST_NBLOCKSIZE : 0)
149 # endif /* not AIX PS/2 */
151 #endif /* HAVE_STRUCT_STAT_ST_BLOCKS */
154 # define ST_NBLOCKS(statbuf) \
155 (S_ISREG ((statbuf).st_mode) \
156 || S_ISDIR ((statbuf).st_mode) \
157 ? (statbuf).st_blocks : 0)
160 #ifndef ST_NBLOCKSIZE
161 # define ST_NBLOCKSIZE 512
166 #define MAX(a, b) ((a) > (b) ? (a) : (b))
168 static bool match_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, bool ignore_case);
170 static char *format_date (struct timespec ts, int kind);
171 static char *ctime_format (struct timespec ts);
180 struct pred_assoc pred_table[] =
182 {pred_amin, "amin "},
184 {pred_anewer, "anewer "},
185 {pred_atime, "atime "},
186 {pred_closeparen, ") "},
187 {pred_cmin, "cmin "},
188 {pred_cnewer, "cnewer "},
190 {pred_ctime, "ctime "},
191 {pred_delete, "delete "},
192 {pred_empty, "empty "},
193 {pred_exec, "exec "},
194 {pred_execdir, "execdir "},
195 {pred_executable, "executable "},
196 {pred_false, "false "},
197 {pred_fprint, "fprint "},
198 {pred_fprint0, "fprint0 "},
199 {pred_fprintf, "fprintf "},
200 {pred_fstype, "fstype "},
202 {pred_group, "group "},
203 {pred_ilname, "ilname "},
204 {pred_iname, "iname "},
205 {pred_inum, "inum "},
206 {pred_ipath, "ipath "},
207 {pred_links, "links "},
208 {pred_lname, "lname "},
210 {pred_mmin, "mmin "},
211 {pred_mtime, "mtime "},
212 {pred_name, "name "},
213 {pred_negate, "not "},
214 {pred_newer, "newer "},
215 {pred_newerXY, "newerXY "},
216 {pred_nogroup, "nogroup "},
217 {pred_nouser, "nouser "},
219 {pred_okdir, "okdir "},
220 {pred_openparen, "( "},
222 {pred_path, "path "},
223 {pred_perm, "perm "},
224 {pred_print, "print "},
225 {pred_print0, "print0 "},
226 {pred_prune, "prune "},
227 {pred_quit, "quit "},
228 {pred_readable, "readable "},
229 {pred_regex, "regex "},
230 {pred_samefile,"samefile "},
231 {pred_size, "size "},
232 {pred_true, "true "},
233 {pred_type, "type "},
235 {pred_used, "used "},
236 {pred_user, "user "},
237 {pred_writable, "writable "},
238 {pred_xtype, "xtype "},
239 {pred_context, "context"},
244 /* Returns ts1 - ts2 */
245 static double ts_difference (struct timespec ts1,
248 double d = difftime (ts1.tv_sec, ts2.tv_sec)
249 + (1.0e-9 * (ts1.tv_nsec - ts2.tv_nsec));
255 compare_ts (struct timespec ts1,
258 if ((ts1.tv_sec == ts2.tv_sec) &&
259 (ts1.tv_nsec == ts2.tv_nsec))
265 double diff = ts_difference (ts1, ts2);
266 return diff < 0.0 ? -1 : +1;
270 /* Predicate processing routines.
272 PATHNAME is the full pathname of the file being checked.
273 *STAT_BUF contains information about PATHNAME.
274 *PRED_PTR contains information for applying the predicate.
276 Return true if the file passes this predicate, false if not. */
281 * Returns true if THE_TIME is
282 * COMP_GT: after the specified time
283 * COMP_LT: before the specified time
284 * COMP_EQ: after the specified time but by not more than WINDOW seconds.
287 pred_timewindow (struct timespec ts, struct predicate const *pred_ptr, int window)
289 switch (pred_ptr->args.reftime.kind)
292 return compare_ts (ts, pred_ptr->args.reftime.ts) > 0;
295 return compare_ts (ts, pred_ptr->args.reftime.ts) < 0;
299 /* consider "find . -mtime 0".
301 * Here, the origin is exactly 86400 seconds before the start
302 * of the program (since -daystart was not specified). This
303 * function will be called with window=86400 and
304 * pred_ptr->args.reftime.ts as the origin. Hence a file
305 * created the instant the program starts will show a time
306 * difference (value of delta) of 86400. Similarly, a file
307 * created exactly 24h ago would be the newest file which was
308 * _not_ created today. So, if delta is 0.0, the file
309 * was not created today. If the delta is 86400, the file
310 * was created this instant.
312 double delta = ts_difference (ts, pred_ptr->args.reftime.ts);
313 return (delta > 0.0 && delta <= window);
322 pred_amin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
325 return pred_timewindow (get_stat_atime(stat_buf), pred_ptr, 60);
329 pred_and (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
331 if (pred_ptr->pred_left == NULL
332 || apply_predicate (pathname, stat_buf, pred_ptr->pred_left))
334 return apply_predicate (pathname, stat_buf, pred_ptr->pred_right);
341 pred_anewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
344 assert (COMP_GT == pred_ptr->args.reftime.kind);
345 return compare_ts (get_stat_atime(stat_buf), pred_ptr->args.reftime.ts) > 0;
349 pred_atime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
352 return pred_timewindow (get_stat_atime(stat_buf), pred_ptr, DAYSECS);
356 pred_closeparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
366 pred_cmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
369 return pred_timewindow (get_stat_ctime(stat_buf), pred_ptr, 60);
373 pred_cnewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
377 assert (COMP_GT == pred_ptr->args.reftime.kind);
378 return compare_ts (get_stat_ctime(stat_buf), pred_ptr->args.reftime.ts) > 0;
382 pred_comma (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
384 if (pred_ptr->pred_left != NULL)
386 apply_predicate (pathname, stat_buf,pred_ptr->pred_left);
388 return apply_predicate (pathname, stat_buf, pred_ptr->pred_right);
392 pred_ctime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
395 return pred_timewindow (get_stat_ctime(stat_buf), pred_ptr, DAYSECS);
399 perform_delete (int flags)
401 return 0 == unlinkat (state.cwd_dir_fd, state.rel_pathname, flags);
406 pred_delete (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
410 if (strcmp (state.rel_pathname, "."))
413 if (state.have_stat && S_ISDIR(stat_buf->st_mode))
414 flags |= AT_REMOVEDIR;
415 if (perform_delete (flags))
423 if ((flags & AT_REMOVEDIR) == 0)
425 /* unlink() operation failed because we should have done rmdir(). */
426 flags |= AT_REMOVEDIR;
427 if (perform_delete (flags))
432 error (0, errno, _("cannot delete %s"),
433 safely_quote_err_filename (0, pathname));
434 /* Previously I had believed that having the -delete action
435 * return false provided the user with control over whether an
436 * error message is issued. While this is true, the policy of
437 * not affecting the exit status is contrary to the POSIX
438 * requirement that diagnostic messages are accompanied by a
439 * nonzero exit status. While -delete is not a POSIX option and
440 * we can therefore opt not to follow POSIX in this case, that
441 * seems somewhat arbitrary and confusing. So, as of
442 * findutils-4.3.11, we also set the exit status in this case.
444 state.exit_status = 1;
455 pred_empty (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
460 if (S_ISDIR (stat_buf->st_mode))
468 if ((fd = openat (state.cwd_dir_fd, state.rel_pathname, O_RDONLY
469 #if defined O_LARGEFILE
474 error (0, errno, "%s", safely_quote_err_filename (0, pathname));
475 state.exit_status = 1;
481 error (0, errno, "%s", safely_quote_err_filename (0, pathname));
482 state.exit_status = 1;
485 for (dp = readdir (d); dp; dp = readdir (d))
487 if (dp->d_name[0] != '.'
488 || (dp->d_name[1] != '\0'
489 && (dp->d_name[1] != '.' || dp->d_name[2] != '\0')))
497 error (0, errno, "%s", safely_quote_err_filename (0, pathname));
498 state.exit_status = 1;
503 else if (S_ISREG (stat_buf->st_mode))
504 return (stat_buf->st_size == 0);
510 /* Initialise exec->wd_for_exec.
512 We save in exec->wd_for_exec the directory whose path relative to
516 initialise_wd_for_exec (struct exec_val *execp, int cwd_fd, const char *dir)
518 execp->wd_for_exec = xmalloc (sizeof (*execp->wd_for_exec));
519 execp->wd_for_exec->name = NULL;
520 execp->wd_for_exec->desc = openat (cwd_fd, dir, O_RDONLY);
521 if (execp->wd_for_exec->desc < 0)
523 set_cloexec_flag (execp->wd_for_exec->desc, true);
529 record_exec_dir (struct exec_val *execp)
531 if (!execp->state.todo)
533 /* Record the WD. If we're using -L or fts chooses to do so for
534 any other reason, state.cwd_dir_fd may in fact not be the
535 directory containing the target file. When this happens,
536 rel_path will contain directory components (since it is the
537 path from state.cwd_dir_fd to the target file).
539 We deal with this by extracting any directory part and using
540 that to adjust what goes into execp->wd_for_exec.
542 if (strchr (state.rel_pathname, '/'))
544 char *dir = mdir_name (state.rel_pathname);
545 bool result = initialise_wd_for_exec (execp, state.cwd_dir_fd, dir);
551 return initialise_wd_for_exec (execp, state.cwd_dir_fd, ".");
559 impl_pred_exec (const char *pathname,
560 struct stat *stat_buf,
561 struct predicate *pred_ptr)
563 struct exec_val *execp = &pred_ptr->args.exec_vec;
566 const bool local = is_exec_in_local_dir (pred_ptr->pred_func);
573 /* For -execdir/-okdir predicates, the parser did not fill in
574 the wd_for_exec member of sturct exec_val. So for those
575 predicates, we do so now.
577 if (!record_exec_dir (execp))
579 error (EXIT_FAILURE, errno,
580 _("Failed to save working directory in order to "
581 "run a command on %s"),
582 safely_quote_err_filename (0, pathname));
585 target = base_name (state.rel_pathname);
586 if ('/' == target[0])
588 /* find / execdir ls -d {} \; */
600 /* For the others (-exec, -ok), the parser should
601 have set wd_for_exec to initial_wd, indicating
602 that the exec should take place from find's initial
605 assert (execp->wd_for_exec == initial_wd);
613 /* Push the argument onto the current list.
614 * The command may or may not be run at this point,
615 * depending on the command line length limits.
617 bc_push_arg (&execp->ctl,
619 target, strlen (target)+1,
623 /* remember that there are pending execdirs. */
624 state.execdirs_outstanding = true;
626 /* POSIX: If the primary expression is punctuated by a plus
627 * sign, the primary shall always evaluate as true
635 for (i=0; i<execp->num_args; ++i)
637 bc_do_insert (&execp->ctl,
639 execp->replace_vec[i],
640 strlen (execp->replace_vec[i]),
642 target, strlen (target),
646 /* Actually invoke the command. */
647 bc_do_exec (&execp->ctl, &execp->state);
648 if (WIFEXITED(execp->last_child_status))
650 if (0 == WEXITSTATUS(execp->last_child_status))
651 result = true; /* The child succeeded. */
660 if (target != pathname)
670 pred_exec (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
672 return impl_pred_exec (pathname, stat_buf, pred_ptr);
676 pred_execdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
679 return impl_pred_exec (state.rel_pathname, stat_buf, pred_ptr);
683 pred_false (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
694 pred_fls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
696 FILE * stream = pred_ptr->args.printf_vec.stream;
697 list_file (pathname, state.cwd_dir_fd, state.rel_pathname, stat_buf,
698 options.start_time.tv_sec,
699 options.output_block_size,
700 pred_ptr->literal_control_chars, stream);
705 pred_fprint (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
710 print_quoted (pred_ptr->args.printf_vec.stream,
711 pred_ptr->args.printf_vec.quote_opts,
712 pred_ptr->args.printf_vec.dest_is_tty,
719 pred_fprint0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
721 FILE * fp = pred_ptr->args.printf_vec.stream;
725 fputs (pathname, fp);
733 mode_to_filetype (mode_t m)
735 #define HANDLE_TYPE(t,letter) if (m==t) { return letter; }
737 HANDLE_TYPE(S_IFREG, "f"); /* regular file */
740 HANDLE_TYPE(S_IFDIR, "d"); /* directory */
743 HANDLE_TYPE(S_IFLNK, "l"); /* symbolic link */
746 HANDLE_TYPE(S_IFSOCK, "s"); /* Unix domain socket */
749 HANDLE_TYPE(S_IFBLK, "b"); /* block device */
752 HANDLE_TYPE(S_IFCHR, "c"); /* character device */
755 HANDLE_TYPE(S_IFIFO, "p"); /* FIFO */
758 HANDLE_TYPE(S_IFDOOR, "D"); /* Door (e.g. on Solaris) */
760 return "U"; /* Unknown */
764 file_sparseness (const struct stat *p)
766 #if defined HAVE_STRUCT_STAT_ST_BLOCKS
769 if (0 == p->st_blocks)
772 return p->st_blocks < 0 ? -HUGE_VAL : HUGE_VAL;
776 double blklen = file_blocksize (p) * (double)p->st_blocks;
777 return blklen / p->st_size;
787 checked_fprintf (struct format_val *dest, const char *fmt, ...)
793 rv = vfprintf (dest->stream, fmt, ap);
795 nonfatal_nontarget_file_error (errno, dest->filename);
800 checked_print_quoted (struct format_val *dest,
801 const char *format, const char *s)
803 int rv = print_quoted (dest->stream, dest->quote_opts, dest->dest_is_tty,
806 nonfatal_nontarget_file_error (errno, dest->filename);
811 checked_fwrite (void *p, size_t siz, size_t nmemb, struct format_val *dest)
813 int items_written = fwrite (p, siz, nmemb, dest->stream);
814 if (items_written < nmemb)
815 nonfatal_nontarget_file_error (errno, dest->filename);
819 checked_fflush (struct format_val *dest)
821 if (0 != fflush (dest->stream))
823 nonfatal_nontarget_file_error (errno, dest->filename);
828 do_fprintf (struct format_val *dest,
829 struct segment *segment,
830 const char *pathname,
831 const struct stat *stat_buf)
833 char hbuf[LONGEST_HUMAN_READABLE + 1];
836 switch (segment->segkind)
838 case KIND_PLAIN: /* Plain text string (no % conversion). */
840 checked_fwrite(segment->text, 1, segment->text_len, dest);
843 case KIND_STOP: /* Terminate argument and flush output. */
845 checked_fwrite (segment->text, 1, segment->text_len, dest);
846 checked_fflush (dest);
850 switch (segment->format_char[0])
852 case 'a': /* atime in `ctime' format. */
853 /* UNTRUSTED, probably unexploitable */
854 checked_fprintf (dest, segment->text, ctime_format (get_stat_atime (stat_buf)));
856 case 'b': /* size in 512-byte blocks */
857 /* UNTRUSTED, probably unexploitable */
858 checked_fprintf (dest, segment->text,
859 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
861 ST_NBLOCKSIZE, 512));
863 case 'c': /* ctime in `ctime' format */
864 /* UNTRUSTED, probably unexploitable */
865 checked_fprintf (dest, segment->text, ctime_format (get_stat_ctime (stat_buf)));
867 case 'd': /* depth in search tree */
868 /* UNTRUSTED, probably unexploitable */
869 checked_fprintf (dest, segment->text, state.curdepth);
871 case 'D': /* Device on which file exists (stat.st_dev) */
873 checked_fprintf (dest, segment->text,
874 human_readable ((uintmax_t) stat_buf->st_dev, hbuf,
875 human_ceiling, 1, 1));
877 case 'f': /* base name of path */
880 char *base = base_name (pathname);
881 checked_print_quoted (dest, segment->text, base);
885 case 'F': /* file system type */
887 checked_print_quoted (dest, segment->text, filesystem_type (stat_buf, pathname));
889 case 'g': /* group name */
891 /* (well, the actual group is selected by the user but
892 * its name was selected by the system administrator)
897 g = getgrgid (stat_buf->st_gid);
900 segment->text[segment->text_len] = 's';
901 checked_fprintf (dest, segment->text, g->gr_name);
910 /*FALLTHROUGH*/ /*...sometimes, so 'G' case.*/
912 case 'G': /* GID number */
913 /* UNTRUSTED, probably unexploitable */
914 checked_fprintf (dest, segment->text,
915 human_readable ((uintmax_t) stat_buf->st_gid, hbuf,
916 human_ceiling, 1, 1));
918 case 'h': /* leading directories part of path */
921 cp = strrchr (pathname, '/');
922 if (cp == NULL) /* No leading directories. */
924 /* If there is no slash in the pathname, we still
925 * print the string because it contains characters
926 * other than just '%s'. The %h expands to ".".
928 checked_print_quoted (dest, segment->text, ".");
932 char *s = strdup (pathname);
933 s[cp - pathname] = 0;
934 checked_print_quoted (dest, segment->text, s);
940 case 'H': /* ARGV element file was found under */
943 char *s = xmalloc (state.starting_path_length+1);
944 memcpy (s, pathname, state.starting_path_length);
945 s[state.starting_path_length] = 0;
946 checked_fprintf (dest, segment->text, s);
951 case 'i': /* inode number */
952 /* UNTRUSTED, but not exploitable I think */
953 checked_fprintf (dest, segment->text,
954 human_readable ((uintmax_t) stat_buf->st_ino, hbuf,
958 case 'k': /* size in 1K blocks */
959 /* UNTRUSTED, but not exploitable I think */
960 checked_fprintf (dest, segment->text,
961 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
963 ST_NBLOCKSIZE, 1024));
965 case 'l': /* object of symlink */
971 if (S_ISLNK (stat_buf->st_mode))
973 linkname = areadlinkat (state.cwd_dir_fd, state.rel_pathname);
974 if (linkname == NULL)
976 nonfatal_target_file_error (errno, pathname);
977 state.exit_status = 1;
982 checked_print_quoted (dest, segment->text, linkname);
986 /* We still need to honour the field width etc., so this is
989 checked_print_quoted (dest, segment->text, "");
996 case 'M': /* mode as 10 chars (eg., "-rwxr-x--x" */
997 /* UNTRUSTED, probably unexploitable */
999 char modestring[16] ;
1000 filemodestring (stat_buf, modestring);
1001 modestring[10] = '\0';
1002 checked_fprintf (dest, segment->text, modestring);
1006 case 'm': /* mode as octal number (perms only) */
1007 /* UNTRUSTED, probably unexploitable */
1009 /* Output the mode portably using the traditional numbers,
1010 even if the host unwisely uses some other numbering
1011 scheme. But help the compiler in the common case where
1012 the host uses the traditional numbering scheme. */
1013 mode_t m = stat_buf->st_mode;
1014 bool traditional_numbering_scheme =
1015 (S_ISUID == 04000 && S_ISGID == 02000 && S_ISVTX == 01000
1016 && S_IRUSR == 00400 && S_IWUSR == 00200 && S_IXUSR == 00100
1017 && S_IRGRP == 00040 && S_IWGRP == 00020 && S_IXGRP == 00010
1018 && S_IROTH == 00004 && S_IWOTH == 00002 && S_IXOTH == 00001);
1019 checked_fprintf (dest, segment->text,
1020 (traditional_numbering_scheme
1022 : ((m & S_ISUID ? 04000 : 0)
1023 | (m & S_ISGID ? 02000 : 0)
1024 | (m & S_ISVTX ? 01000 : 0)
1025 | (m & S_IRUSR ? 00400 : 0)
1026 | (m & S_IWUSR ? 00200 : 0)
1027 | (m & S_IXUSR ? 00100 : 0)
1028 | (m & S_IRGRP ? 00040 : 0)
1029 | (m & S_IWGRP ? 00020 : 0)
1030 | (m & S_IXGRP ? 00010 : 0)
1031 | (m & S_IROTH ? 00004 : 0)
1032 | (m & S_IWOTH ? 00002 : 0)
1033 | (m & S_IXOTH ? 00001 : 0))));
1037 case 'n': /* number of links */
1038 /* UNTRUSTED, probably unexploitable */
1039 checked_fprintf (dest, segment->text,
1040 human_readable ((uintmax_t) stat_buf->st_nlink,
1046 case 'p': /* pathname */
1048 checked_print_quoted (dest, segment->text, pathname);
1051 case 'P': /* pathname with ARGV element stripped */
1053 if (state.curdepth > 0)
1055 cp = pathname + state.starting_path_length;
1057 /* Move past the slash between the ARGV element
1058 and the rest of the pathname. But if the ARGV element
1059 ends in a slash, we didn't add another, so we've
1060 already skipped past it. */
1067 checked_print_quoted (dest, segment->text, cp);
1070 case 's': /* size in bytes */
1071 /* UNTRUSTED, probably unexploitable */
1072 checked_fprintf (dest, segment->text,
1073 human_readable ((uintmax_t) stat_buf->st_size,
1074 hbuf, human_ceiling, 1, 1));
1077 case 'S': /* sparseness */
1078 /* UNTRUSTED, probably unexploitable */
1079 checked_fprintf (dest, segment->text, file_sparseness (stat_buf));;
1082 case 't': /* mtime in `ctime' format */
1083 /* UNTRUSTED, probably unexploitable */
1084 checked_fprintf (dest, segment->text,
1085 ctime_format (get_stat_mtime (stat_buf)));
1088 case 'u': /* user name */
1090 /* (well, the actual user is selected by the user on systems
1091 * where chown is not restricted, but the user name was
1092 * selected by the system administrator)
1097 p = getpwuid (stat_buf->st_uid);
1100 segment->text[segment->text_len] = 's';
1101 checked_fprintf (dest, segment->text, p->pw_name);
1106 /* FALLTHROUGH*/ /* .. to case U */
1108 case 'U': /* UID number */
1109 /* UNTRUSTED, probably unexploitable */
1110 checked_fprintf (dest, segment->text,
1111 human_readable ((uintmax_t) stat_buf->st_uid, hbuf,
1112 human_ceiling, 1, 1));
1115 /* %Y: type of file system entry like `ls -l`:
1116 * (d,-,l,s,p,b,c,n) n=nonexistent (symlink)
1118 case 'Y': /* in case of symlink */
1122 if (S_ISLNK (stat_buf->st_mode))
1125 /* If we would normally follow links, do not do so.
1126 * If we would normally not follow links, do so.
1128 if ((following_links () ? optionp_stat : optionl_stat)
1129 (state.rel_pathname, &sbuf) != 0)
1131 if ( errno == ENOENT )
1133 checked_fprintf (dest, segment->text, "N");
1136 else if ( errno == ELOOP )
1138 checked_fprintf (dest, segment->text, "L");
1143 checked_fprintf (dest, segment->text, "?");
1144 error (0, errno, "%s",
1145 safely_quote_err_filename (0, pathname));
1151 checked_fprintf (dest, segment->text,
1152 mode_to_filetype (sbuf.st_mode & S_IFMT));
1154 #endif /* S_ISLNK */
1157 checked_fprintf (dest, segment->text,
1158 mode_to_filetype (stat_buf->st_mode & S_IFMT));
1166 checked_fprintf (dest, segment->text,
1167 mode_to_filetype (stat_buf->st_mode & S_IFMT));
1171 case 'Z': /* SELinux security context */
1173 security_context_t scontext;
1174 int rv = (*options.x_getfilecon) (state.cwd_dir_fd, state.rel_pathname,
1178 /* If getfilecon fails, there will in the general case
1179 still be some text to print. We just make %Z expand
1180 to an empty string. */
1181 checked_fprintf (dest, segment->text, "");
1183 error (0, errno, _("getfilecon failed: %s"),
1184 safely_quote_err_filename (0, pathname));
1185 state.exit_status = 1;
1189 checked_fprintf (dest, segment->text, scontext);
1195 /* end of KIND_FORMAT case */
1201 pred_fprintf (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1203 struct format_val *dest = &pred_ptr->args.printf_vec;
1204 struct segment *segment;
1206 for (segment = dest->segment; segment; segment = segment->next)
1208 if ( (KIND_FORMAT == segment->segkind) && segment->format_char[1]) /* Component of date. */
1213 switch (segment->format_char[0])
1216 ts = get_stat_atime (stat_buf);
1220 ts = get_stat_birthtime (stat_buf);
1221 if ('@' == segment->format_char[1])
1224 valid = (ts.tv_nsec >= 0);
1227 ts = get_stat_ctime (stat_buf);
1231 ts = get_stat_mtime (stat_buf);
1238 /* We trust the output of format_date not to contain
1239 * nasty characters, though the value of the date
1240 * is itself untrusted data.
1245 checked_fprintf (dest, segment->text,
1246 format_date (ts, segment->format_char[1]));
1250 /* The specified timestamp is not available, output
1251 * nothing for the timestamp, but use the rest (so that
1252 * for example find foo -printf '[%Bs] %p\n' can print
1256 checked_fprintf (dest, segment->text, "");
1261 /* Print a segment which is not a date. */
1262 do_fprintf (dest, segment, pathname, stat_buf);
1269 pred_fstype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1273 if (strcmp (filesystem_type (stat_buf, pathname), pred_ptr->args.str) == 0)
1280 pred_gid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1284 switch (pred_ptr->args.numinfo.kind)
1287 if (stat_buf->st_gid > pred_ptr->args.numinfo.l_val)
1291 if (stat_buf->st_gid < pred_ptr->args.numinfo.l_val)
1295 if (stat_buf->st_gid == pred_ptr->args.numinfo.l_val)
1303 pred_group (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1307 if (pred_ptr->args.gid == stat_buf->st_gid)
1314 pred_ilname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1316 return match_lname (pathname, stat_buf, pred_ptr, true);
1319 /* Common code between -name, -iname. PATHNAME is being visited, STR
1320 is name to compare basename against, and FLAGS are passed to
1321 fnmatch. Recall that 'find / -name /' is one of the few times where a '/'
1322 in the -name must actually find something. */
1324 pred_name_common (const char *pathname, const char *str, int flags)
1327 /* We used to use last_component() here, but that would not allow us to modify the
1328 * input string, which is const. We could optimise by duplicating the string only
1329 * if we need to modify it, and I'll do that if there is a measurable
1330 * performance difference on a machine built after 1990...
1332 char *base = base_name (pathname);
1333 /* remove trailing slashes, but leave "/" or "//foo" unchanged. */
1334 strip_trailing_slashes (base);
1336 /* FNM_PERIOD is not used here because POSIX requires that it not be.
1337 * See http://standards.ieee.org/reading/ieee/interp/1003-2-92_int/pasc-1003.2-126.html
1339 b = fnmatch (str, base, flags) == 0;
1345 pred_iname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1348 return pred_name_common (pathname, pred_ptr->args.str, FNM_CASEFOLD);
1352 pred_inum (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1356 assert (stat_buf->st_ino != 0);
1358 switch (pred_ptr->args.numinfo.kind)
1361 if (stat_buf->st_ino > pred_ptr->args.numinfo.l_val)
1365 if (stat_buf->st_ino < pred_ptr->args.numinfo.l_val)
1369 if (stat_buf->st_ino == pred_ptr->args.numinfo.l_val)
1377 pred_ipath (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1381 if (fnmatch (pred_ptr->args.str, pathname, FNM_CASEFOLD) == 0)
1387 pred_links (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1391 switch (pred_ptr->args.numinfo.kind)
1394 if (stat_buf->st_nlink > pred_ptr->args.numinfo.l_val)
1398 if (stat_buf->st_nlink < pred_ptr->args.numinfo.l_val)
1402 if (stat_buf->st_nlink == pred_ptr->args.numinfo.l_val)
1410 pred_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1412 return match_lname (pathname, stat_buf, pred_ptr, false);
1416 match_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, bool ignore_case)
1420 if (S_ISLNK (stat_buf->st_mode))
1422 char *linkname = areadlinkat (state.cwd_dir_fd, state.rel_pathname);
1425 if (fnmatch (pred_ptr->args.str, linkname,
1426 ignore_case ? FNM_CASEFOLD : 0) == 0)
1431 nonfatal_target_file_error (errno, pathname);
1432 state.exit_status = 1;
1436 #endif /* S_ISLNK */
1441 pred_ls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1443 return pred_fls (pathname, stat_buf, pred_ptr);
1447 pred_mmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1450 return pred_timewindow (get_stat_mtime(stat_buf), pred_ptr, 60);
1454 pred_mtime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1457 return pred_timewindow (get_stat_mtime(stat_buf), pred_ptr, DAYSECS);
1461 pred_name (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1464 return pred_name_common (pathname, pred_ptr->args.str, 0);
1468 pred_negate (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1470 return !apply_predicate (pathname, stat_buf, pred_ptr->pred_right);
1474 pred_newer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1478 assert (COMP_GT == pred_ptr->args.reftime.kind);
1479 return compare_ts (get_stat_mtime(stat_buf), pred_ptr->args.reftime.ts) > 0;
1483 pred_newerXY (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1486 bool collected = false;
1488 assert (COMP_GT == pred_ptr->args.reftime.kind);
1490 switch (pred_ptr->args.reftime.xval)
1493 assert (pred_ptr->args.reftime.xval != XVAL_TIME);
1497 ts = get_stat_atime (stat_buf);
1501 case XVAL_BIRTHTIME:
1502 ts = get_stat_birthtime (stat_buf);
1504 if (ts.tv_nsec < 0);
1506 /* XXX: Cannot determine birth time. Warn once. */
1507 error (0, 0, _("WARNING: cannot determine birth time of file %s"),
1508 safely_quote_err_filename (0, pathname));
1514 ts = get_stat_ctime (stat_buf);
1519 ts = get_stat_mtime (stat_buf);
1525 return compare_ts (ts, pred_ptr->args.reftime.ts) > 0;
1529 pred_nogroup (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1535 extern char *gid_unused;
1537 return gid_unused[(unsigned) stat_buf->st_gid];
1539 return getgrgid (stat_buf->st_gid) == NULL;
1544 pred_nouser (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1547 extern char *uid_unused;
1554 return uid_unused[(unsigned) stat_buf->st_uid];
1556 return getpwuid (stat_buf->st_uid) == NULL;
1562 is_ok (const char *program, const char *arg)
1565 /* The draft open standard requires that, in the POSIX locale,
1566 the last non-blank character of this prompt be '?'.
1567 The exact format is not specified.
1568 This standard does not have requirements for locales other than POSIX
1570 /* XXX: printing UNTRUSTED data here. */
1571 fprintf (stderr, _("< %s ... %s > ? "), program, arg);
1577 pred_ok (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1579 if (is_ok (pred_ptr->args.exec_vec.replace_vec[0], pathname))
1580 return impl_pred_exec (pathname, stat_buf, pred_ptr);
1586 pred_okdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1588 if (is_ok (pred_ptr->args.exec_vec.replace_vec[0], pathname))
1589 return impl_pred_exec (state.rel_pathname, stat_buf, pred_ptr);
1595 pred_openparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1604 pred_or (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1606 if (pred_ptr->pred_left == NULL
1607 || !apply_predicate (pathname, stat_buf, pred_ptr->pred_left))
1609 return apply_predicate (pathname, stat_buf, pred_ptr->pred_right);
1616 pred_path (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1619 if (fnmatch (pred_ptr->args.str, pathname, 0) == 0)
1625 pred_perm (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1627 mode_t mode = stat_buf->st_mode;
1628 mode_t perm_val = pred_ptr->args.perm.val[S_ISDIR (mode) != 0];
1630 switch (pred_ptr->args.perm.kind)
1633 return (mode & perm_val) == perm_val;
1637 /* True if any of the bits set in the mask are also set in the file's mode.
1640 * Otherwise, if onum is prefixed by a hyphen, the primary shall
1641 * evaluate as true if at least all of the bits specified in
1642 * onum that are also set in the octal mask 07777 are set.
1644 * Eric Blake's interpretation is that the mode argument is zero,
1648 return true; /* Savannah bug 14748; we used to return false */
1650 return (mode & perm_val) != 0;
1654 return (mode & MODE_ALL) == perm_val;
1665 pred_executable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1671 /* As for access, the check is performed with the real user id. */
1672 return 0 == faccessat (state.cwd_dir_fd, state.rel_pathname, X_OK, 0);
1676 pred_readable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1682 /* As for access, the check is performed with the real user id. */
1683 return 0 == faccessat (state.cwd_dir_fd, state.rel_pathname, R_OK, 0);
1687 pred_writable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1693 /* As for access, the check is performed with the real user id. */
1694 return 0 == faccessat (state.cwd_dir_fd, state.rel_pathname, W_OK, 0);
1698 pred_print (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1703 print_quoted (pred_ptr->args.printf_vec.stream,
1704 pred_ptr->args.printf_vec.quote_opts,
1705 pred_ptr->args.printf_vec.dest_is_tty,
1711 pred_print0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1713 return pred_fprint0(pathname, stat_buf, pred_ptr);
1717 pred_prune (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1722 if (options.do_dir_first == true) { /* no effect with -depth */
1723 assert (state.have_stat);
1724 if (stat_buf != NULL &&
1725 S_ISDIR(stat_buf->st_mode))
1726 state.stop_at_current_level = true;
1729 /* findutils used to return options.do_dir_first here, so that -prune
1730 * returns true only if -depth is not in effect. But POSIX requires
1731 * that -prune always evaluate as true.
1737 pred_quit (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1743 /* Run any cleanups. This includes executing any command lines
1744 * we have partly built but not executed.
1748 /* Since -exec and friends don't leave child processes running in the
1749 * background, there is no need to wait for them here.
1751 exit (state.exit_status); /* 0 for success, etc. */
1755 pred_regex (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1757 int len = strlen (pathname);
1759 if (re_match (pred_ptr->args.regex, pathname, len, 0,
1760 (struct re_registers *) NULL) == len)
1766 pred_size (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1771 f_val = ((stat_buf->st_size / pred_ptr->args.size.blocksize)
1772 + (stat_buf->st_size % pred_ptr->args.size.blocksize != 0));
1773 switch (pred_ptr->args.size.kind)
1776 if (f_val > pred_ptr->args.size.size)
1780 if (f_val < pred_ptr->args.size.size)
1784 if (f_val == pred_ptr->args.size.size)
1792 pred_samefile (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1794 /* Potential optimisation: because of the loop protection, we always
1795 * know the device of the current directory, hence the device number
1796 * of the file we're currently considering. If -L is not in effect,
1797 * and the device number of the file we're looking for is not the
1798 * same as the device number of the current directory, this
1799 * predicate cannot return true. Hence there would be no need to
1800 * stat the file we're looking at.
1802 * For the moment, we simply compare inode numbers, which should cut
1803 * down greatly on the number of calls to stat. Some of the
1804 * remainder will be unnecessary, but the additional complexity
1805 * probably isn't worthwhile.
1809 /* We will often still have an fd open on the file under consideration,
1810 * but that's just to ensure inode number stability by maintaining
1811 * a reference to it; we don't need the file for anything else.
1813 if (stat_buf->st_ino)
1815 if (stat_buf->st_ino != pred_ptr->args.samefileid.ino)
1818 /* Now stat the file to check the device number. */
1819 if (0 == get_statinfo (pathname, state.rel_pathname, stat_buf))
1821 /* the repeated test here is necessary in case stat_buf.st_ino had been zero. */
1822 return stat_buf->st_ino == pred_ptr->args.samefileid.ino
1823 && stat_buf->st_dev == pred_ptr->args.samefileid.dev;
1827 /* get_statinfo will already have emitted an error message. */
1833 pred_true (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1842 pred_type (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1845 mode_t type = pred_ptr->args.type;
1847 assert (state.have_type);
1849 if (0 == state.type)
1851 /* This can sometimes happen with broken NFS servers.
1852 * See Savannah bug #16378.
1859 if (state.have_stat)
1860 mode = stat_buf->st_mode;
1865 /* POSIX system; check `mode' the slow way. */
1866 if ((S_ISBLK (mode) && type == S_IFBLK)
1867 || (S_ISCHR (mode) && type == S_IFCHR)
1868 || (S_ISDIR (mode) && type == S_IFDIR)
1869 || (S_ISREG (mode) && type == S_IFREG)
1871 || (S_ISLNK (mode) && type == S_IFLNK)
1874 || (S_ISFIFO (mode) && type == S_IFIFO)
1877 || (S_ISSOCK (mode) && type == S_IFSOCK)
1880 || (S_ISDOOR (mode) && type == S_IFDOOR)
1884 /* Unix system; check `mode' the fast way. */
1885 if ((mode & S_IFMT) == type)
1893 pred_uid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1896 switch (pred_ptr->args.numinfo.kind)
1899 if (stat_buf->st_uid > pred_ptr->args.numinfo.l_val)
1903 if (stat_buf->st_uid < pred_ptr->args.numinfo.l_val)
1907 if (stat_buf->st_uid == pred_ptr->args.numinfo.l_val)
1915 pred_used (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1917 struct timespec delta, at, ct;
1921 /* TODO: this needs to be retested carefully (manually, if necessary) */
1922 at = get_stat_atime (stat_buf);
1923 ct = get_stat_ctime (stat_buf);
1924 delta.tv_sec = at.tv_sec - ct.tv_sec;
1925 delta.tv_nsec = at.tv_nsec - ct.tv_nsec;
1926 if (delta.tv_nsec < 0)
1928 delta.tv_nsec += 1000000000;
1931 return pred_timewindow (delta, pred_ptr, DAYSECS);
1935 pred_user (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1938 if (pred_ptr->args.uid == stat_buf->st_uid)
1945 pred_xtype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1947 struct stat sbuf; /* local copy, not stat_buf because we're using a different stat method */
1948 int (*ystat) (const char*, struct stat *p);
1950 /* If we would normally stat the link itself, stat the target instead.
1951 * If we would normally follow the link, stat the link itself instead.
1953 if (following_links ())
1954 ystat = optionp_stat;
1956 ystat = optionl_stat;
1958 set_stat_placeholders (&sbuf);
1959 if ((*ystat) (state.rel_pathname, &sbuf) != 0)
1961 if (following_links () && errno == ENOENT)
1963 /* If we failed to follow the symlink,
1964 * fall back on looking at the symlink itself.
1966 /* Mimic behavior of ls -lL. */
1967 return (pred_type (pathname, stat_buf, pred_ptr));
1971 error (0, errno, "%s", safely_quote_err_filename (0, pathname));
1972 state.exit_status = 1;
1976 /* Now that we have our stat() information, query it in the same
1977 * way that -type does.
1979 return (pred_type (pathname, &sbuf, pred_ptr));
1984 pred_context (const char *pathname, struct stat *stat_buf,
1985 struct predicate *pred_ptr)
1987 security_context_t scontext;
1988 int rv = (*options.x_getfilecon) (state.cwd_dir_fd, state.rel_pathname,
1992 error (0, errno, _("getfilecon failed: %s"),
1993 safely_quote_err_filename (0, pathname));
1997 rv = (fnmatch (pred_ptr->args.scontext, scontext, 0) == 0);
2003 /* 1) fork to get a child; parent remembers the child pid
2004 2) child execs the command requested
2005 3) parent waits for child; checks for proper pid of child
2009 ret errno status(h) status(l)
2011 pid x signal# 0177 stopped
2012 pid x exit arg 0 term by _exit
2013 pid x 0 signal # term by signal
2014 -1 EINTR parent got signal
2015 -1 other some other kind of error
2017 Return true only if the pid matches, status(l) is
2018 zero, and the exit arg (status high) is 0.
2019 Otherwise return false, possibly printing an error message. */
2023 prep_child_for_exec (bool close_stdin, const struct saved_cwd *wd)
2028 const char inputfile[] = "/dev/null";
2032 error (0, errno, _("Cannot close standard input"));
2037 if (open (inputfile, O_RDONLY
2038 #if defined O_LARGEFILE
2043 /* This is not entirely fatal, since
2044 * executing the child with a closed
2045 * stdin is almost as good as executing it
2046 * with its stdin attached to /dev/null.
2048 error (0, errno, "%s", safely_quote_err_filename (0, inputfile));
2049 /* do not set ok=false, it is OK to continue anyway. */
2054 /* Even if DebugSearch is set, don't announce our change of
2055 * directory, since we're not going to emit a subsequent
2056 * announcement of a call to stat() anyway, as we're about to exec
2059 if (0 != restore_cwd (wd))
2061 error (0, errno, _("Failed to change directory"));
2073 launch (struct buildcmd_control *ctl, void *usercontext, int argc, char **argv)
2076 static int first_time = 1;
2077 struct exec_val *execp = usercontext;
2079 /* Make sure output of command doesn't get mixed with find output. */
2083 /* Make sure to listen for the kids. */
2087 signal (SIGCHLD, SIG_DFL);
2090 child_pid = fork ();
2091 if (child_pid == -1)
2092 error (EXIT_FAILURE, errno, _("cannot fork"));
2095 /* We are the child. */
2096 assert (NULL != execp->wd_for_exec);
2097 if (!prep_child_for_exec (execp->close_stdin, execp->wd_for_exec))
2103 if (fd_leak_check_is_enabled ())
2105 complain_about_leaky_fds ();
2109 if (bc_args_exceed_testing_limit (argv))
2112 execvp (argv[0], argv);
2113 /* TODO: use a pipe to pass back the errno value, like xargs does */
2114 error (0, errno, "%s",
2115 safely_quote_err_filename (0, argv[0]));
2119 while (waitpid (child_pid, &(execp->last_child_status), 0) == (pid_t) -1)
2123 error (0, errno, _("error waiting for %s"),
2124 safely_quote_err_filename (0, argv[0]));
2125 state.exit_status = 1;
2126 return 0; /* FAIL */
2130 if (WIFSIGNALED (execp->last_child_status))
2132 error (0, 0, _("%s terminated by signal %d"),
2133 quotearg_n_style (0, options.err_quoting_style, argv[0]),
2134 WTERMSIG (execp->last_child_status));
2136 if (execp->multiple)
2138 /* -exec \; just returns false if the invoked command fails.
2139 * -exec {} + returns true if the invoked command fails, but
2140 * sets the program exit status.
2142 state.exit_status = 1;
2148 if (0 == WEXITSTATUS (execp->last_child_status))
2154 if (execp->multiple)
2156 /* -exec \; just returns false if the invoked command fails.
2157 * -exec {} + returns true if the invoked command fails, but
2158 * sets the program exit status.
2160 state.exit_status = 1;
2162 /* The child failed, but this is the exec callback. We
2163 * don't want to run the child again in this case anwyay.
2165 return 1; /* FAIL (but don't try again) */
2172 scan_for_digit_differences (const char *p, const char *q,
2173 size_t *first, size_t *n)
2178 for (i=0; p[i] && q[i]; i++)
2182 if (!isdigit ((unsigned char)q[i]) || !isdigit ((unsigned char)q[i]))
2195 /* Still in the first sequence of differing digits. */
2200 /* More than one differing contiguous character sequence. */
2208 /* strings are different lengths. */
2216 do_time_format (const char *fmt, const struct tm *p, const char *ns, size_t ns_size)
2218 static char *buf = NULL;
2219 static size_t buf_size;
2220 char *timefmt = NULL;
2221 struct tm altered_time;
2224 /* If the format expands to nothing (%p in some locales, for
2225 * example), strftime can return 0. We actually want to distinguish
2226 * the error case where the buffer is too short, so we just prepend
2227 * an otherwise uninteresting character to prevent the no-output
2230 timefmt = xmalloc (strlen (fmt) + 2u);
2231 sprintf (timefmt, "_%s", fmt);
2233 /* altered_time is a similar time, but in which both
2234 * digits of the seconds field are different.
2237 if (altered_time.tm_sec >= 11)
2238 altered_time.tm_sec -= 11;
2240 altered_time.tm_sec += 11;
2242 /* If we call strftime() with buf_size=0, the program will coredump
2243 * on Solaris, since it unconditionally writes the terminating null
2247 buf = xmalloc (buf_size);
2250 /* I'm not sure that Solaris will return 0 when the buffer is too small.
2251 * Therefore we do not check for (buf_used != 0) as the termination
2254 size_t buf_used = strftime (buf, buf_size, timefmt, p);
2255 if (buf_used /* Conforming POSIX system */
2256 && (buf_used < buf_size)) /* Solaris workaround */
2259 size_t i = 0, n = 0;
2260 size_t final_len = (buf_used
2263 buf = xrealloc (buf, final_len);
2264 altbuf = xmalloc (final_len);
2265 strftime (altbuf, buf_size, timefmt, &altered_time);
2267 /* Find the seconds digits; they should be the only changed part.
2268 * In theory the result of the two formatting operations could differ in
2269 * more than just one sequence of decimal digits (for example %X might
2270 * in theory return a spelled-out time like "thirty seconds past noon").
2271 * When that happens, we just avoid inserting the nanoseconds field.
2273 if (scan_for_digit_differences (buf, altbuf, &i, &n)
2274 && (2==n) && !isdigit ((unsigned char)buf[i+n]))
2276 const size_t end_of_seconds = i + n;
2277 const size_t suffix_len = buf_used-(end_of_seconds)+1;
2279 /* Move the tail (including the \0). Note that this
2280 * is a move of an overlapping memory block, so we
2281 * must use memmove instead of memcpy. Then insert
2282 * the nanoseconds (but not its trailing \0).
2284 assert (end_of_seconds + ns_size + suffix_len == final_len);
2285 memmove (buf+end_of_seconds+ns_size,
2288 memcpy (buf+i+n, ns, ns_size);
2292 /* No seconds digits. No need to insert anything. */
2294 /* The first character of buf is the underscore, which we actually
2302 buf = x2nrealloc (buf, &buf_size, 2u);
2309 /* Return a static string formatting the time WHEN according to the
2310 * strftime format character KIND.
2312 * This function contains a number of assertions. These look like
2313 * runtime checks of the results of computations, which would be a
2314 * problem since external events should not be tested for with
2315 * "assert" (instead you should use "if"). However, they are not
2316 * really runtime checks. The assertions actually exist to verify
2317 * that the various buffers are correctly sized.
2320 format_date (struct timespec ts, int kind)
2322 /* In theory, we use an extra 10 characters for 9 digits of
2323 * nanoseconds and 1 for the decimal point. However, the real
2324 * world is more complex than that.
2326 * For example, some systems return junk in the tv_nsec part of
2327 * st_birthtime. An example of this is the NetBSD-4.0-RELENG kernel
2328 * (at Sat Mar 24 18:46:46 2007) running a NetBSD-3.1-RELEASE
2329 * runtime and examining files on an msdos filesytem. So for that
2330 * reason we set NS_BUF_LEN to 32, which is simply "long enough" as
2331 * opposed to "exactly the right size". Note that the behaviour of
2332 * NetBSD appears to be a result of the use of uninitialised data,
2333 * as it's not 100% reproducible (more like 25%).
2337 DATE_LEN_PERCENT_APLUS=21 /* length of result of %A+ (it's longer than %c)*/
2339 static char buf[128u+10u + MAX(DATE_LEN_PERCENT_APLUS,
2340 MAX (LONGEST_HUMAN_READABLE + 2, NS_BUF_LEN+64+200))];
2341 char ns_buf[NS_BUF_LEN]; /* -.9999999990 (- sign can happen!)*/
2342 int charsprinted, need_ns_suffix;
2346 /* human_readable() assumes we pass a buffer which is at least as
2347 * long as LONGEST_HUMAN_READABLE. We use an assertion here to
2348 * ensure that no nasty unsigned overflow happend in our calculation
2349 * of the size of buf. Do the assertion here rather than in the
2350 * code for %@ so that we find the problem quickly if it exists. If
2351 * you want to submit a patch to move this into the if statement, go
2352 * ahead, I'll apply it. But include performance timings
2353 * demonstrating that the performance difference is actually
2356 verify (sizeof (buf) >= LONGEST_HUMAN_READABLE);
2361 /* Format the main part of the time. */
2364 strcpy (fmt, "%F+%T");
2373 /* %a, %c, and %t are handled in ctime_format() */
2390 /* Format the nanoseconds part. Leave a trailing zero to
2391 * discourage people from writing scripts which extract the
2392 * fractional part of the timestamp by using column offsets.
2393 * The reason for discouraging this is that in the future, the
2394 * granularity may not be nanoseconds.
2396 charsprinted = snprintf (ns_buf, NS_BUF_LEN, ".%09ld0", (long int)ts.tv_nsec);
2397 assert (charsprinted < NS_BUF_LEN);
2407 tm = localtime (&ts.tv_sec);
2410 char *s = do_time_format (fmt, tm, ns_buf, charsprinted);
2416 /* If we get to here, either the format was %@, or we have fallen back to it
2417 * because strftime failed.
2421 uintmax_t w = ts.tv_sec;
2422 size_t used, len, remaining;
2424 /* XXX: note that we are negating an unsigned type which is the
2425 * widest possible unsigned type.
2427 char *p = human_readable (ts.tv_sec < 0 ? -w : w, buf + 1,
2428 human_ceiling, 1, 1);
2430 assert (p < (buf + (sizeof buf)));
2432 *--p = '-'; /* XXX: Ugh, relying on internal details of human_readable(). */
2434 /* Add the nanoseconds part. Because we cannot enforce a
2435 * particlar implementation of human_readable, we cannot assume
2436 * any particular value for (p-buf). So we need to be careful
2437 * that there is enough space remaining in the buffer.
2442 used = (p-buf) + len; /* Offset into buf of current end */
2443 assert (sizeof buf > used); /* Ensure we can perform subtraction safely. */
2444 remaining = sizeof buf - used - 1u; /* allow space for NUL */
2446 if (strlen (ns_buf) >= remaining)
2449 "charsprinted=%ld but remaining=%lu: ns_buf=%s",
2450 (long)charsprinted, (unsigned long)remaining, ns_buf);
2452 assert (strlen (ns_buf) < remaining);
2459 static const char *weekdays[] =
2461 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
2463 static char * months[] =
2465 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2466 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2471 ctime_format (struct timespec ts)
2473 const struct tm * ptm;
2474 #define TIME_BUF_LEN 1024u
2475 static char resultbuf[TIME_BUF_LEN];
2478 ptm = localtime (&ts.tv_sec);
2481 assert (ptm->tm_wday >= 0);
2482 assert (ptm->tm_wday < 7);
2483 assert (ptm->tm_mon >= 0);
2484 assert (ptm->tm_mon < 12);
2485 assert (ptm->tm_hour >= 0);
2486 assert (ptm->tm_hour < 24);
2487 assert (ptm->tm_min < 60);
2488 assert (ptm->tm_sec <= 61); /* allows 2 leap seconds. */
2490 /* wkday mon mday hh:mm:ss.nnnnnnnnn yyyy */
2491 nout = snprintf (resultbuf, TIME_BUF_LEN,
2492 "%3s %3s %2d %02d:%02d:%02d.%010ld %04d",
2493 weekdays[ptm->tm_wday],
2494 months[ptm->tm_mon],
2499 (long int)ts.tv_nsec,
2500 1900 + ptm->tm_year);
2502 assert (nout < TIME_BUF_LEN);
2507 /* The time cannot be represented as a struct tm.
2508 Output it as an integer. */
2509 return format_date (ts, '@');
2513 /* Copy STR into BUF and trim blanks from the end of BUF.
2517 blank_rtrim (str, buf)
2526 i = strlen (buf) - 1;
2527 while ((i >= 0) && ((buf[i] == ' ') || buf[i] == '\t'))
2533 /* Print out the predicate list starting at NODE. */
2535 print_list (FILE *fp, struct predicate *node)
2537 struct predicate *cur;
2543 fprintf (fp, "[%s] ", blank_rtrim (cur->p_name, name));
2544 cur = cur->pred_next;
2549 /* Print out the predicate list starting at NODE. */
2551 print_parenthesised (FILE *fp, struct predicate *node)
2557 if ((pred_is (node, pred_or) || pred_is (node, pred_and))
2558 && node->pred_left == NULL)
2560 /* We print "<nothing> or X" as just "X"
2561 * We print "<nothing> and X" as just "X"
2563 print_parenthesised(fp, node->pred_right);
2567 if (node->pred_left || node->pred_right)
2571 fprintf (fp, "%s", " ( ");
2572 print_optlist (fp, node);
2574 fprintf (fp, "%s", " ) ");
2580 print_optlist (FILE *fp, const struct predicate *p)
2584 print_parenthesised (fp, p->pred_left);
2587 p->need_stat ? "[call stat] " : "",
2588 p->need_type ? "[need type] " : "",
2589 p->need_inum ? "[need inum] " : "");
2590 print_predicate (fp, p);
2591 fprintf (fp, " [%g] ", p->est_success_rate);
2592 if (options.debug_options & DebugSuccessRates)
2594 fprintf (fp, "[%ld/%ld", p->perf.successes, p->perf.visits);
2597 double real_rate = (double)p->perf.successes / (double)p->perf.visits;
2598 fprintf (fp, "=%g] ", real_rate);
2602 fprintf (fp, "=_] ");
2605 print_parenthesised (fp, p->pred_right);
2609 void show_success_rates (const struct predicate *p)
2611 if (options.debug_options & DebugSuccessRates)
2613 fprintf (stderr, "Predicate success rates after completion:\n");
2614 print_optlist (stderr, p);
2615 fprintf (stderr, "\n");
2623 /* If _NDEBUG is defined, the assertions will do nothing. Hence
2624 * there is no point in having a function body for pred_sanity_check()
2625 * if that preprocessor macro is defined.
2628 pred_sanity_check (const struct predicate *predicates)
2630 /* Do nothing, since assert is a no-op with _NDEBUG set */
2635 pred_sanity_check (const struct predicate *predicates)
2637 const struct predicate *p;
2639 for (p=predicates; p != NULL; p=p->pred_next)
2641 /* All predicates must do something. */
2642 assert (p->pred_func != NULL);
2644 /* All predicates must have a parser table entry. */
2645 assert (p->parser_entry != NULL);
2647 /* If the parser table tells us that just one predicate function is
2648 * possible, verify that that is still the one that is in effect.
2649 * If the parser has NULL for the predicate function, that means that
2650 * the parse_xxx function fills it in, so we can't check it.
2652 if (p->parser_entry->pred_func)
2654 assert (p->parser_entry->pred_func == p->pred_func);
2657 switch (p->parser_entry->type)
2659 /* Options all take effect during parsing, so there should
2660 * be no predicate entries corresponding to them. Hence we
2661 * should not see any ARG_OPTION or ARG_POSITIONAL_OPTION
2664 * This is a silly way of coding this test, but it prevents
2665 * a compiler warning (i.e. otherwise it would think that
2666 * there would be case statements missing).
2669 case ARG_POSITIONAL_OPTION:
2670 assert (p->parser_entry->type != ARG_OPTION);
2671 assert (p->parser_entry->type != ARG_POSITIONAL_OPTION);
2675 assert (p->side_effects); /* actions have side effects. */
2676 if (!pred_is (p, pred_prune) && !pred_is(p, pred_quit))
2678 /* actions other than -prune and -quit should
2679 * inhibit the default -print
2681 assert (p->no_default_print);
2685 /* We happen to know that the only user of ARG_SPECIAL_PARSE
2686 * is a test, so handle it like ARG_TEST.
2688 case ARG_SPECIAL_PARSE:
2690 case ARG_PUNCTUATION:
2692 /* Punctuation and tests should have no side
2693 * effects and not inhibit default print.
2695 assert (!p->no_default_print);
2696 assert (!p->side_effects);