From 0f4ef4c46e5e7bc45fd0f2a850a205024f5a2d71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Duval?= Date: Sat, 29 Nov 2008 20:41:23 +0000 Subject: [PATCH] updated findutils to 4.2.33 (sorry, not latest). git-svn-id: file:///srv/svn/repos/haiku/haiku/trunk@28750 a95241bf-73f2-0310-859d-f6bbb57e9c96 --- src/bin/findutils/COPYING | 845 ++- src/bin/findutils/Jamfile | 1 + src/bin/findutils/README | 28 +- src/bin/findutils/config.h | 1088 +++- src/bin/findutils/find/Jamfile | 3 +- src/bin/findutils/find/defs.h | 531 +- src/bin/findutils/find/find.1 | 990 +++- src/bin/findutils/find/find.c | 2077 ++++++- src/bin/findutils/find/fstype.c | 500 +- src/bin/findutils/find/parser.c | 2296 ++++--- src/bin/findutils/find/pred.c | 1694 ++++-- src/bin/findutils/find/tree.c | 168 +- src/bin/findutils/find/util.c | 127 +- src/bin/findutils/find/version.c | 4 +- src/bin/findutils/findutils.rdef | 8 +- src/bin/findutils/gnulib/Jamfile | 3 + src/bin/findutils/gnulib/lib/Jamfile | 58 + src/bin/findutils/{ => gnulib}/lib/alloca.c | 171 +- src/bin/findutils/gnulib/lib/alloca.h | 55 + src/bin/findutils/gnulib/lib/alloca.in.h | 54 + .../gnulib/lib/areadlink-with-size.c | 108 + src/bin/findutils/gnulib/lib/areadlink.h | 23 + src/bin/findutils/gnulib/lib/argmatch.c | 277 + src/bin/findutils/gnulib/lib/argmatch.h | 102 + src/bin/findutils/gnulib/lib/at-func.c | 85 + src/bin/findutils/gnulib/lib/basename.c | 128 + src/bin/findutils/gnulib/lib/binary-io.h | 63 + .../findutils/gnulib/lib/canonicalize-lgpl.c | 362 ++ src/bin/findutils/gnulib/lib/canonicalize.c | 337 ++ src/bin/findutils/gnulib/lib/canonicalize.h | 52 + src/bin/findutils/gnulib/lib/chdir-long.c | 264 + src/bin/findutils/gnulib/lib/chdir-long.h | 34 + src/bin/findutils/gnulib/lib/chown.c | 103 + src/bin/findutils/gnulib/lib/close-stream.c | 75 + src/bin/findutils/gnulib/lib/close-stream.h | 2 + src/bin/findutils/gnulib/lib/closein.c | 111 + src/bin/findutils/gnulib/lib/closein.h | 32 + src/bin/findutils/gnulib/lib/closeout.c | 85 + src/bin/findutils/gnulib/lib/closeout.h | 32 + src/bin/findutils/gnulib/lib/configmake.h | 25 + src/bin/findutils/gnulib/lib/creat-safer.c | 31 + src/bin/findutils/gnulib/lib/dirent.in.h | 45 + src/bin/findutils/gnulib/lib/dirfd.c | 28 + src/bin/findutils/gnulib/lib/dirfd.h | 28 + src/bin/findutils/gnulib/lib/dirname.c | 84 + src/bin/findutils/gnulib/lib/dirname.h | 69 + src/bin/findutils/gnulib/lib/dup-safer.c | 44 + src/bin/findutils/gnulib/lib/dup2.c | 57 + src/bin/findutils/gnulib/lib/error.c | 338 ++ src/bin/findutils/gnulib/lib/error.h | 65 + src/bin/findutils/gnulib/lib/exitfail.c | 24 + src/bin/findutils/gnulib/lib/exitfail.h | 18 + src/bin/findutils/gnulib/lib/fchdir.c | 282 + src/bin/findutils/gnulib/lib/fchmodat.c | 49 + src/bin/findutils/gnulib/lib/fchown-stub.c | 16 + src/bin/findutils/gnulib/lib/fchownat.c | 48 + src/bin/findutils/gnulib/lib/fcntl--.h | 27 + src/bin/findutils/gnulib/lib/fcntl-safer.h | 23 + src/bin/findutils/gnulib/lib/fcntl.h | 121 + src/bin/findutils/gnulib/lib/fcntl.in.h | 120 + src/bin/findutils/gnulib/lib/fd-safer.c | 56 + src/bin/findutils/gnulib/lib/fflush.c | 109 + src/bin/findutils/gnulib/lib/file-set.c | 74 + src/bin/findutils/gnulib/lib/file-set.h | 12 + .../findutils/{ => gnulib}/lib/fileblocks.c | 56 +- src/bin/findutils/gnulib/lib/filemode.c | 180 + src/bin/findutils/gnulib/lib/filemode.h | 32 + src/bin/findutils/gnulib/lib/filenamecat.c | 102 + src/bin/findutils/gnulib/lib/filenamecat.h | 24 + src/bin/findutils/gnulib/lib/fnmatch.c | 354 ++ src/bin/findutils/gnulib/lib/fnmatch.h | 66 + src/bin/findutils/gnulib/lib/fnmatch.in.h | 65 + src/bin/findutils/gnulib/lib/fnmatch_loop.c | 1210 ++++ src/bin/findutils/gnulib/lib/fopen-safer.c | 67 + src/bin/findutils/gnulib/lib/fpending.c | 29 + src/bin/findutils/gnulib/lib/fpending.h | 33 + src/bin/findutils/gnulib/lib/fpurge.c | 121 + src/bin/findutils/gnulib/lib/fpurge.h | 38 + src/bin/findutils/gnulib/lib/freadahead.c | 66 + src/bin/findutils/gnulib/lib/freadahead.h | 36 + src/bin/findutils/gnulib/lib/freading.c | 50 + src/bin/findutils/gnulib/lib/freading.h | 53 + src/bin/findutils/gnulib/lib/fseeko.c | 120 + src/bin/findutils/gnulib/lib/fstatat.c | 56 + src/bin/findutils/gnulib/lib/ftello.c | 54 + src/bin/findutils/gnulib/lib/getcwd.c | 427 ++ src/bin/findutils/gnulib/lib/getdelim.c | 133 + src/bin/findutils/gnulib/lib/getline.c | 29 + src/bin/findutils/gnulib/lib/getopt.c | 1190 ++++ src/bin/findutils/gnulib/lib/getopt.in.h | 225 + src/bin/findutils/{ => gnulib}/lib/getopt1.c | 94 +- src/bin/findutils/gnulib/lib/getopt_int.h | 130 + src/bin/findutils/gnulib/lib/gettext.h | 270 + src/bin/findutils/gnulib/lib/hash-pjw.c | 40 + src/bin/findutils/gnulib/lib/hash-pjw.h | 23 + src/bin/findutils/gnulib/lib/hash-triple.c | 77 + src/bin/findutils/gnulib/lib/hash-triple.h | 22 + src/bin/findutils/gnulib/lib/hash.c | 1049 ++++ src/bin/findutils/gnulib/lib/hash.h | 87 + src/bin/findutils/gnulib/lib/human.c | 471 ++ src/bin/findutils/gnulib/lib/human.h | 84 + src/bin/findutils/gnulib/lib/idcache.c | 227 + src/bin/findutils/gnulib/lib/idcache.h | 11 + src/bin/findutils/gnulib/lib/intprops.h | 77 + src/bin/findutils/gnulib/lib/inttypes.h | 1124 ++++ src/bin/findutils/gnulib/lib/inttypes.in.h | 1095 ++++ src/bin/findutils/gnulib/lib/lchown.c | 62 + src/bin/findutils/gnulib/lib/localcharset.c | 460 ++ src/bin/findutils/gnulib/lib/localcharset.h | 41 + src/bin/findutils/gnulib/lib/lseek.c | 62 + src/bin/findutils/gnulib/lib/lstat.c | 75 + src/bin/findutils/gnulib/lib/lstat.h | 23 + src/bin/findutils/gnulib/lib/malloc.c | 57 + src/bin/findutils/gnulib/lib/malloca.c | 137 + src/bin/findutils/gnulib/lib/malloca.h | 124 + src/bin/findutils/gnulib/lib/memcmp.c | 361 ++ src/bin/findutils/gnulib/lib/mempcpy.c | 29 + src/bin/findutils/gnulib/lib/memrchr.c | 189 + src/bin/findutils/{ => gnulib}/lib/memset.c | 17 +- src/bin/findutils/gnulib/lib/mkdirat.c | 42 + src/bin/findutils/gnulib/lib/mktime.c | 663 +++ src/bin/findutils/gnulib/lib/modechange.c | 385 ++ src/bin/findutils/gnulib/lib/modechange.h | 30 + src/bin/findutils/gnulib/lib/mountlist.c | 884 +++ src/bin/findutils/gnulib/lib/mountlist.h | 40 + src/bin/findutils/gnulib/lib/open-safer.c | 49 + src/bin/findutils/gnulib/lib/openat-die.c | 50 + src/bin/findutils/gnulib/lib/openat-priv.h | 54 + src/bin/findutils/gnulib/lib/openat-proc.c | 94 + src/bin/findutils/gnulib/lib/openat.c | 268 + src/bin/findutils/gnulib/lib/openat.h | 126 + src/bin/findutils/gnulib/lib/pathmax.h | 47 + src/bin/findutils/gnulib/lib/pipe-safer.c | 56 + src/bin/findutils/gnulib/lib/progname.c | 49 + src/bin/findutils/gnulib/lib/progname.h | 60 + src/bin/findutils/gnulib/lib/quote.c | 40 + src/bin/findutils/gnulib/lib/quote.h | 21 + src/bin/findutils/gnulib/lib/quotearg.c | 696 +++ src/bin/findutils/gnulib/lib/quotearg.h | 139 + src/bin/findutils/gnulib/lib/readlink.c | 49 + src/bin/findutils/gnulib/lib/realloc.c | 87 + src/bin/findutils/gnulib/lib/regcomp.c | 3832 ++++++++++++ src/bin/findutils/gnulib/lib/regex.c | 71 + src/bin/findutils/gnulib/lib/regex.h | 675 +++ src/bin/findutils/gnulib/lib/regex_internal.c | 1741 ++++++ src/bin/findutils/gnulib/lib/regex_internal.h | 857 +++ src/bin/findutils/gnulib/lib/regexec.c | 4399 ++++++++++++++ src/bin/findutils/gnulib/lib/rpmatch.c | 78 + src/bin/findutils/gnulib/lib/same-inode.h | 25 + src/bin/findutils/gnulib/lib/same.c | 125 + src/bin/findutils/gnulib/lib/same.h | 26 + src/bin/findutils/gnulib/lib/save-cwd.c | 102 + src/bin/findutils/gnulib/lib/save-cwd.h | 33 + src/bin/findutils/gnulib/lib/savedir.c | 136 + src/bin/findutils/gnulib/lib/savedir.h | 26 + src/bin/findutils/gnulib/lib/stat-macros.h | 3 + src/bin/findutils/gnulib/lib/stdbool.in.h | 119 + src/bin/findutils/gnulib/lib/stdint.h | 517 ++ src/bin/findutils/gnulib/lib/stdint.in.h | 516 ++ src/bin/findutils/gnulib/lib/stdio--.h | 27 + src/bin/findutils/gnulib/lib/stdio-safer.h | 23 + src/bin/findutils/gnulib/lib/stdio.h | 411 ++ src/bin/findutils/gnulib/lib/stdio.in.h | 382 ++ src/bin/findutils/gnulib/lib/stdlib.h | 214 + src/bin/findutils/gnulib/lib/stdlib.in.h | 185 + src/bin/findutils/gnulib/lib/stpcpy.c | 48 + src/bin/findutils/gnulib/lib/strdup.c | 55 + src/bin/findutils/gnulib/lib/strerror.c | 49 + src/bin/findutils/gnulib/lib/strftime.c | 1461 +++++ src/bin/findutils/gnulib/lib/strftime.h | 20 + src/bin/findutils/gnulib/lib/string.h | 549 ++ src/bin/findutils/gnulib/lib/string.in.h | 520 ++ src/bin/findutils/gnulib/lib/stripslash.c | 44 + src/bin/findutils/gnulib/lib/strndup.c | 37 + src/bin/findutils/gnulib/lib/strnlen.c | 31 + src/bin/findutils/gnulib/lib/strtoimax.c | 75 + src/bin/findutils/gnulib/lib/strtol.c | 435 ++ src/bin/findutils/gnulib/lib/strtoll.c | 32 + src/bin/findutils/gnulib/lib/strtoul.c | 19 + src/bin/findutils/gnulib/lib/strtoull.c | 26 + src/bin/findutils/gnulib/lib/strtoumax.c | 2 + src/bin/findutils/gnulib/lib/sys/stat.h | 280 + src/bin/findutils/gnulib/lib/sys_stat.in.h | 280 + src/bin/findutils/gnulib/lib/time.h | 115 + src/bin/findutils/gnulib/lib/time.in.h | 114 + src/bin/findutils/gnulib/lib/time_r.c | 47 + src/bin/findutils/gnulib/lib/unistd--.h | 27 + src/bin/findutils/gnulib/lib/unistd-safer.h | 22 + src/bin/findutils/gnulib/lib/unistd.h | 318 + src/bin/findutils/gnulib/lib/unistd.in.h | 317 + src/bin/findutils/gnulib/lib/verify.h | 140 + src/bin/findutils/gnulib/lib/wchar.in.h | 82 + src/bin/findutils/gnulib/lib/wctype.in.h | 161 + src/bin/findutils/gnulib/lib/xalloc-die.c | 41 + src/bin/findutils/gnulib/lib/xalloc.h | 270 + src/bin/findutils/gnulib/lib/xgetcwd.c | 40 + src/bin/findutils/gnulib/lib/xgetcwd.h | 17 + src/bin/findutils/gnulib/lib/xmalloc.c | 122 + src/bin/findutils/gnulib/lib/xstrndup.c | 36 + src/bin/findutils/gnulib/lib/xstrndup.h | 23 + src/bin/findutils/gnulib/lib/xstrtol-error.c | 98 + src/bin/findutils/gnulib/lib/xstrtol.c | 228 + src/bin/findutils/gnulib/lib/xstrtol.h | 78 + src/bin/findutils/gnulib/lib/xstrtoul.c | 6 + src/bin/findutils/gnulib/lib/xstrtoumax.c | 6 + src/bin/findutils/gnulib/lib/yesno.c | 63 + src/bin/findutils/gnulib/lib/yesno.h | 24 + src/bin/findutils/lib/Jamfile | 25 +- src/bin/findutils/lib/buildcmd.c | 513 ++ src/bin/findutils/lib/buildcmd.h | 129 + src/bin/findutils/lib/dirname.c | 70 - src/bin/findutils/lib/error.c | 119 - src/bin/findutils/lib/extendbuf.c | 104 + src/bin/findutils/lib/extendbuf.h | 25 + src/bin/findutils/lib/filemode.c | 237 - src/bin/findutils/lib/fnmatch.c | 200 - src/bin/findutils/lib/fnmatch.h | 67 - src/bin/findutils/lib/forcefindlib.c | 49 + src/bin/findutils/lib/getline.c | 126 - src/bin/findutils/lib/getopt.c | 748 --- src/bin/findutils/lib/getopt.h | 129 - src/bin/findutils/lib/gnulib-version.c | 2 + src/bin/findutils/lib/gnulib-version.h | 19 + src/bin/findutils/lib/idcache.c | 210 - src/bin/findutils/lib/listfile.c | 272 +- src/bin/findutils/lib/listfile.h | 26 + src/bin/findutils/lib/memcmp.c | 32 - src/bin/findutils/lib/mktime.c | 502 -- src/bin/findutils/lib/modechange.c | 341 -- src/bin/findutils/lib/modechange.h | 55 - src/bin/findutils/lib/modetype.h | 28 +- src/bin/findutils/lib/nextelem.c | 32 +- src/bin/findutils/lib/nextelem.h | 26 + src/bin/findutils/lib/pathmax.h | 53 - src/bin/findutils/lib/printquoted.c | 85 + src/bin/findutils/lib/printquoted.h | 34 + src/bin/findutils/lib/qmark.c | 237 + src/bin/findutils/lib/regex.c | 5251 ----------------- src/bin/findutils/lib/regex.h | 487 -- src/bin/findutils/lib/regexprops.c | 505 ++ src/bin/findutils/lib/regextype.c | 157 + src/bin/findutils/lib/regextype.h | 27 + src/bin/findutils/lib/savedir.c | 131 - src/bin/findutils/lib/savedirinfo.c | 386 ++ src/bin/findutils/lib/savedirinfo.h | 72 + src/bin/findutils/lib/stpcpy.c | 32 - src/bin/findutils/lib/strdup.c | 43 - src/bin/findutils/lib/strftime.c | 469 -- src/bin/findutils/lib/strspn.c | 40 - src/bin/findutils/lib/strstr.c | 44 - src/bin/findutils/lib/strtol.c | 186 - src/bin/findutils/lib/wait.h | 15 +- src/bin/findutils/lib/waitpid.c | 81 + src/bin/findutils/lib/xgetcwd.c | 78 - src/bin/findutils/lib/xmalloc.c | 95 - src/bin/findutils/lib/xstrdup.c | 36 - src/bin/findutils/locate/Jamfile | 5 +- src/bin/findutils/locate/bigram.c | 41 +- src/bin/findutils/locate/code.c | 115 +- src/bin/findutils/locate/frcode.c | 158 +- src/bin/findutils/locate/locate.1 | 155 +- src/bin/findutils/locate/locate.c | 1469 ++++- src/bin/findutils/locate/locatedb.5 | 18 +- src/bin/findutils/locate/locatedb.h | 39 +- src/bin/findutils/locate/updatedb.1 | 89 +- src/bin/findutils/locate/updatedb.sh | 255 +- src/bin/findutils/xargs/Jamfile | 3 +- src/bin/findutils/xargs/xargs.1 | 336 +- src/bin/findutils/xargs/xargs.c | 1005 ++-- 269 files changed, 53602 insertions(+), 13629 deletions(-) create mode 100644 src/bin/findutils/gnulib/Jamfile create mode 100644 src/bin/findutils/gnulib/lib/Jamfile rename src/bin/findutils/{ => gnulib}/lib/alloca.c (84%) create mode 100644 src/bin/findutils/gnulib/lib/alloca.h create mode 100644 src/bin/findutils/gnulib/lib/alloca.in.h create mode 100644 src/bin/findutils/gnulib/lib/areadlink-with-size.c create mode 100644 src/bin/findutils/gnulib/lib/areadlink.h create mode 100644 src/bin/findutils/gnulib/lib/argmatch.c create mode 100644 src/bin/findutils/gnulib/lib/argmatch.h create mode 100644 src/bin/findutils/gnulib/lib/at-func.c create mode 100644 src/bin/findutils/gnulib/lib/basename.c create mode 100644 src/bin/findutils/gnulib/lib/binary-io.h create mode 100644 src/bin/findutils/gnulib/lib/canonicalize-lgpl.c create mode 100644 src/bin/findutils/gnulib/lib/canonicalize.c create mode 100644 src/bin/findutils/gnulib/lib/canonicalize.h create mode 100644 src/bin/findutils/gnulib/lib/chdir-long.c create mode 100644 src/bin/findutils/gnulib/lib/chdir-long.h create mode 100644 src/bin/findutils/gnulib/lib/chown.c create mode 100644 src/bin/findutils/gnulib/lib/close-stream.c create mode 100644 src/bin/findutils/gnulib/lib/close-stream.h create mode 100644 src/bin/findutils/gnulib/lib/closein.c create mode 100644 src/bin/findutils/gnulib/lib/closein.h create mode 100644 src/bin/findutils/gnulib/lib/closeout.c create mode 100644 src/bin/findutils/gnulib/lib/closeout.h create mode 100644 src/bin/findutils/gnulib/lib/configmake.h create mode 100644 src/bin/findutils/gnulib/lib/creat-safer.c create mode 100644 src/bin/findutils/gnulib/lib/dirent.in.h create mode 100644 src/bin/findutils/gnulib/lib/dirfd.c create mode 100644 src/bin/findutils/gnulib/lib/dirfd.h create mode 100644 src/bin/findutils/gnulib/lib/dirname.c create mode 100644 src/bin/findutils/gnulib/lib/dirname.h create mode 100644 src/bin/findutils/gnulib/lib/dup-safer.c create mode 100644 src/bin/findutils/gnulib/lib/dup2.c create mode 100644 src/bin/findutils/gnulib/lib/error.c create mode 100644 src/bin/findutils/gnulib/lib/error.h create mode 100644 src/bin/findutils/gnulib/lib/exitfail.c create mode 100644 src/bin/findutils/gnulib/lib/exitfail.h create mode 100644 src/bin/findutils/gnulib/lib/fchdir.c create mode 100644 src/bin/findutils/gnulib/lib/fchmodat.c create mode 100644 src/bin/findutils/gnulib/lib/fchown-stub.c create mode 100644 src/bin/findutils/gnulib/lib/fchownat.c create mode 100644 src/bin/findutils/gnulib/lib/fcntl--.h create mode 100644 src/bin/findutils/gnulib/lib/fcntl-safer.h create mode 100644 src/bin/findutils/gnulib/lib/fcntl.h create mode 100644 src/bin/findutils/gnulib/lib/fcntl.in.h create mode 100644 src/bin/findutils/gnulib/lib/fd-safer.c create mode 100644 src/bin/findutils/gnulib/lib/fflush.c create mode 100644 src/bin/findutils/gnulib/lib/file-set.c create mode 100644 src/bin/findutils/gnulib/lib/file-set.h rename src/bin/findutils/{ => gnulib}/lib/fileblocks.c (52%) create mode 100644 src/bin/findutils/gnulib/lib/filemode.c create mode 100644 src/bin/findutils/gnulib/lib/filemode.h create mode 100644 src/bin/findutils/gnulib/lib/filenamecat.c create mode 100644 src/bin/findutils/gnulib/lib/filenamecat.h create mode 100644 src/bin/findutils/gnulib/lib/fnmatch.c create mode 100644 src/bin/findutils/gnulib/lib/fnmatch.h create mode 100644 src/bin/findutils/gnulib/lib/fnmatch.in.h create mode 100644 src/bin/findutils/gnulib/lib/fnmatch_loop.c create mode 100644 src/bin/findutils/gnulib/lib/fopen-safer.c create mode 100644 src/bin/findutils/gnulib/lib/fpending.c create mode 100644 src/bin/findutils/gnulib/lib/fpending.h create mode 100644 src/bin/findutils/gnulib/lib/fpurge.c create mode 100644 src/bin/findutils/gnulib/lib/fpurge.h create mode 100644 src/bin/findutils/gnulib/lib/freadahead.c create mode 100644 src/bin/findutils/gnulib/lib/freadahead.h create mode 100644 src/bin/findutils/gnulib/lib/freading.c create mode 100644 src/bin/findutils/gnulib/lib/freading.h create mode 100644 src/bin/findutils/gnulib/lib/fseeko.c create mode 100644 src/bin/findutils/gnulib/lib/fstatat.c create mode 100644 src/bin/findutils/gnulib/lib/ftello.c create mode 100644 src/bin/findutils/gnulib/lib/getcwd.c create mode 100644 src/bin/findutils/gnulib/lib/getdelim.c create mode 100644 src/bin/findutils/gnulib/lib/getline.c create mode 100644 src/bin/findutils/gnulib/lib/getopt.c create mode 100644 src/bin/findutils/gnulib/lib/getopt.in.h rename src/bin/findutils/{ => gnulib}/lib/getopt1.c (55%) create mode 100644 src/bin/findutils/gnulib/lib/getopt_int.h create mode 100644 src/bin/findutils/gnulib/lib/gettext.h create mode 100644 src/bin/findutils/gnulib/lib/hash-pjw.c create mode 100644 src/bin/findutils/gnulib/lib/hash-pjw.h create mode 100644 src/bin/findutils/gnulib/lib/hash-triple.c create mode 100644 src/bin/findutils/gnulib/lib/hash-triple.h create mode 100644 src/bin/findutils/gnulib/lib/hash.c create mode 100644 src/bin/findutils/gnulib/lib/hash.h create mode 100644 src/bin/findutils/gnulib/lib/human.c create mode 100644 src/bin/findutils/gnulib/lib/human.h create mode 100644 src/bin/findutils/gnulib/lib/idcache.c create mode 100644 src/bin/findutils/gnulib/lib/idcache.h create mode 100644 src/bin/findutils/gnulib/lib/intprops.h create mode 100644 src/bin/findutils/gnulib/lib/inttypes.h create mode 100644 src/bin/findutils/gnulib/lib/inttypes.in.h create mode 100644 src/bin/findutils/gnulib/lib/lchown.c create mode 100644 src/bin/findutils/gnulib/lib/localcharset.c create mode 100644 src/bin/findutils/gnulib/lib/localcharset.h create mode 100644 src/bin/findutils/gnulib/lib/lseek.c create mode 100644 src/bin/findutils/gnulib/lib/lstat.c create mode 100644 src/bin/findutils/gnulib/lib/lstat.h create mode 100644 src/bin/findutils/gnulib/lib/malloc.c create mode 100644 src/bin/findutils/gnulib/lib/malloca.c create mode 100644 src/bin/findutils/gnulib/lib/malloca.h create mode 100644 src/bin/findutils/gnulib/lib/memcmp.c create mode 100644 src/bin/findutils/gnulib/lib/mempcpy.c create mode 100644 src/bin/findutils/gnulib/lib/memrchr.c rename src/bin/findutils/{ => gnulib}/lib/memset.c (65%) create mode 100644 src/bin/findutils/gnulib/lib/mkdirat.c create mode 100644 src/bin/findutils/gnulib/lib/mktime.c create mode 100644 src/bin/findutils/gnulib/lib/modechange.c create mode 100644 src/bin/findutils/gnulib/lib/modechange.h create mode 100644 src/bin/findutils/gnulib/lib/mountlist.c create mode 100644 src/bin/findutils/gnulib/lib/mountlist.h create mode 100644 src/bin/findutils/gnulib/lib/open-safer.c create mode 100644 src/bin/findutils/gnulib/lib/openat-die.c create mode 100644 src/bin/findutils/gnulib/lib/openat-priv.h create mode 100644 src/bin/findutils/gnulib/lib/openat-proc.c create mode 100644 src/bin/findutils/gnulib/lib/openat.c create mode 100644 src/bin/findutils/gnulib/lib/openat.h create mode 100644 src/bin/findutils/gnulib/lib/pathmax.h create mode 100644 src/bin/findutils/gnulib/lib/pipe-safer.c create mode 100644 src/bin/findutils/gnulib/lib/progname.c create mode 100644 src/bin/findutils/gnulib/lib/progname.h create mode 100644 src/bin/findutils/gnulib/lib/quote.c create mode 100644 src/bin/findutils/gnulib/lib/quote.h create mode 100644 src/bin/findutils/gnulib/lib/quotearg.c create mode 100644 src/bin/findutils/gnulib/lib/quotearg.h create mode 100644 src/bin/findutils/gnulib/lib/readlink.c create mode 100644 src/bin/findutils/gnulib/lib/realloc.c create mode 100644 src/bin/findutils/gnulib/lib/regcomp.c create mode 100644 src/bin/findutils/gnulib/lib/regex.c create mode 100644 src/bin/findutils/gnulib/lib/regex.h create mode 100644 src/bin/findutils/gnulib/lib/regex_internal.c create mode 100644 src/bin/findutils/gnulib/lib/regex_internal.h create mode 100644 src/bin/findutils/gnulib/lib/regexec.c create mode 100644 src/bin/findutils/gnulib/lib/rpmatch.c create mode 100644 src/bin/findutils/gnulib/lib/same-inode.h create mode 100644 src/bin/findutils/gnulib/lib/same.c create mode 100644 src/bin/findutils/gnulib/lib/same.h create mode 100644 src/bin/findutils/gnulib/lib/save-cwd.c create mode 100644 src/bin/findutils/gnulib/lib/save-cwd.h create mode 100644 src/bin/findutils/gnulib/lib/savedir.c create mode 100644 src/bin/findutils/gnulib/lib/savedir.h create mode 100644 src/bin/findutils/gnulib/lib/stat-macros.h create mode 100644 src/bin/findutils/gnulib/lib/stdbool.in.h create mode 100644 src/bin/findutils/gnulib/lib/stdint.h create mode 100644 src/bin/findutils/gnulib/lib/stdint.in.h create mode 100644 src/bin/findutils/gnulib/lib/stdio--.h create mode 100644 src/bin/findutils/gnulib/lib/stdio-safer.h create mode 100644 src/bin/findutils/gnulib/lib/stdio.h create mode 100644 src/bin/findutils/gnulib/lib/stdio.in.h create mode 100644 src/bin/findutils/gnulib/lib/stdlib.h create mode 100644 src/bin/findutils/gnulib/lib/stdlib.in.h create mode 100644 src/bin/findutils/gnulib/lib/stpcpy.c create mode 100644 src/bin/findutils/gnulib/lib/strdup.c create mode 100644 src/bin/findutils/gnulib/lib/strerror.c create mode 100644 src/bin/findutils/gnulib/lib/strftime.c create mode 100644 src/bin/findutils/gnulib/lib/strftime.h create mode 100644 src/bin/findutils/gnulib/lib/string.h create mode 100644 src/bin/findutils/gnulib/lib/string.in.h create mode 100644 src/bin/findutils/gnulib/lib/stripslash.c create mode 100644 src/bin/findutils/gnulib/lib/strndup.c create mode 100644 src/bin/findutils/gnulib/lib/strnlen.c create mode 100644 src/bin/findutils/gnulib/lib/strtoimax.c create mode 100644 src/bin/findutils/gnulib/lib/strtol.c create mode 100644 src/bin/findutils/gnulib/lib/strtoll.c create mode 100644 src/bin/findutils/gnulib/lib/strtoul.c create mode 100644 src/bin/findutils/gnulib/lib/strtoull.c create mode 100644 src/bin/findutils/gnulib/lib/strtoumax.c create mode 100644 src/bin/findutils/gnulib/lib/sys/stat.h create mode 100644 src/bin/findutils/gnulib/lib/sys_stat.in.h create mode 100644 src/bin/findutils/gnulib/lib/time.h create mode 100644 src/bin/findutils/gnulib/lib/time.in.h create mode 100644 src/bin/findutils/gnulib/lib/time_r.c create mode 100644 src/bin/findutils/gnulib/lib/unistd--.h create mode 100644 src/bin/findutils/gnulib/lib/unistd-safer.h create mode 100644 src/bin/findutils/gnulib/lib/unistd.h create mode 100644 src/bin/findutils/gnulib/lib/unistd.in.h create mode 100644 src/bin/findutils/gnulib/lib/verify.h create mode 100644 src/bin/findutils/gnulib/lib/wchar.in.h create mode 100644 src/bin/findutils/gnulib/lib/wctype.in.h create mode 100644 src/bin/findutils/gnulib/lib/xalloc-die.c create mode 100644 src/bin/findutils/gnulib/lib/xalloc.h create mode 100644 src/bin/findutils/gnulib/lib/xgetcwd.c create mode 100644 src/bin/findutils/gnulib/lib/xgetcwd.h create mode 100644 src/bin/findutils/gnulib/lib/xmalloc.c create mode 100644 src/bin/findutils/gnulib/lib/xstrndup.c create mode 100644 src/bin/findutils/gnulib/lib/xstrndup.h create mode 100644 src/bin/findutils/gnulib/lib/xstrtol-error.c create mode 100644 src/bin/findutils/gnulib/lib/xstrtol.c create mode 100644 src/bin/findutils/gnulib/lib/xstrtol.h create mode 100644 src/bin/findutils/gnulib/lib/xstrtoul.c create mode 100644 src/bin/findutils/gnulib/lib/xstrtoumax.c create mode 100644 src/bin/findutils/gnulib/lib/yesno.c create mode 100644 src/bin/findutils/gnulib/lib/yesno.h create mode 100644 src/bin/findutils/lib/buildcmd.c create mode 100644 src/bin/findutils/lib/buildcmd.h delete mode 100644 src/bin/findutils/lib/dirname.c delete mode 100644 src/bin/findutils/lib/error.c create mode 100644 src/bin/findutils/lib/extendbuf.c create mode 100644 src/bin/findutils/lib/extendbuf.h delete mode 100644 src/bin/findutils/lib/filemode.c delete mode 100644 src/bin/findutils/lib/fnmatch.c delete mode 100644 src/bin/findutils/lib/fnmatch.h create mode 100644 src/bin/findutils/lib/forcefindlib.c delete mode 100644 src/bin/findutils/lib/getline.c delete mode 100644 src/bin/findutils/lib/getopt.c delete mode 100644 src/bin/findutils/lib/getopt.h create mode 100644 src/bin/findutils/lib/gnulib-version.c create mode 100644 src/bin/findutils/lib/gnulib-version.h delete mode 100644 src/bin/findutils/lib/idcache.c create mode 100644 src/bin/findutils/lib/listfile.h delete mode 100644 src/bin/findutils/lib/memcmp.c delete mode 100644 src/bin/findutils/lib/mktime.c delete mode 100644 src/bin/findutils/lib/modechange.c delete mode 100644 src/bin/findutils/lib/modechange.h create mode 100644 src/bin/findutils/lib/nextelem.h delete mode 100644 src/bin/findutils/lib/pathmax.h create mode 100644 src/bin/findutils/lib/printquoted.c create mode 100644 src/bin/findutils/lib/printquoted.h create mode 100644 src/bin/findutils/lib/qmark.c delete mode 100644 src/bin/findutils/lib/regex.c delete mode 100644 src/bin/findutils/lib/regex.h create mode 100644 src/bin/findutils/lib/regexprops.c create mode 100644 src/bin/findutils/lib/regextype.c create mode 100644 src/bin/findutils/lib/regextype.h delete mode 100644 src/bin/findutils/lib/savedir.c create mode 100644 src/bin/findutils/lib/savedirinfo.c create mode 100644 src/bin/findutils/lib/savedirinfo.h delete mode 100644 src/bin/findutils/lib/stpcpy.c delete mode 100644 src/bin/findutils/lib/strdup.c delete mode 100644 src/bin/findutils/lib/strftime.c delete mode 100644 src/bin/findutils/lib/strspn.c delete mode 100644 src/bin/findutils/lib/strstr.c delete mode 100644 src/bin/findutils/lib/strtol.c create mode 100644 src/bin/findutils/lib/waitpid.c delete mode 100644 src/bin/findutils/lib/xgetcwd.c delete mode 100644 src/bin/findutils/lib/xmalloc.c delete mode 100644 src/bin/findutils/lib/xstrdup.c diff --git a/src/bin/findutils/COPYING b/src/bin/findutils/COPYING index a43ea2126f..4432540474 100644 --- a/src/bin/findutils/COPYING +++ b/src/bin/findutils/COPYING @@ -1,285 +1,627 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 675 Mass Ave, Cambridge, MA 02139, USA + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". + TERMS AND CONDITIONS -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. + 0. Definitions. - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. + "This License" refers to version 3 of the GNU General Public License. -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. + A "covered work" means either the unmodified Program or a work based +on the Program. - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. + 1. Source Code. - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. + The Corresponding Source for a work in source code form is that +same work. - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. + 2. Basic Permissions. - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of this License. - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. + 13. Use with the GNU Affero General Public License. -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. + 14. Revised Versions of this License. - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. - NO WARRANTY + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. + 15. Disclaimer of Warranty. - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. END OF TERMS AND CONDITIONS - - Appendix: How to Apply These Terms to Your New Programs + + How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it @@ -287,15 +629,15 @@ free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least +state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. - Copyright (C) 19yy + Copyright (C) - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or + the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, @@ -304,36 +646,31 @@ the "copyright" line and a pointer to where the full notice is found. GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: - Gnomovision version 69, Copyright (C) 19yy name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. diff --git a/src/bin/findutils/Jamfile b/src/bin/findutils/Jamfile index 217334b6a8..9ceab271a8 100644 --- a/src/bin/findutils/Jamfile +++ b/src/bin/findutils/Jamfile @@ -1,5 +1,6 @@ SubDir HAIKU_TOP src bin findutils ; +SubInclude HAIKU_TOP src bin findutils gnulib ; SubInclude HAIKU_TOP src bin findutils lib ; SubInclude HAIKU_TOP src bin findutils find ; SubInclude HAIKU_TOP src bin findutils locate ; diff --git a/src/bin/findutils/README b/src/bin/findutils/README index beff140830..be967a2224 100644 --- a/src/bin/findutils/README +++ b/src/bin/findutils/README @@ -1,12 +1,21 @@ This package contains the GNU find, xargs, and locate programs. find -and xargs comply with POSIX 1003.2, as far as I know. They also -support some additional options, some borrowed from Unix and some -unique to GNU. +and xargs comply with POSIX 1003.2, as far as I know (with the +exception of the "+" modifier for the "-exec" action, which isn't +implemented yet). They also support a large number of additional +options, some borrowed from Unix and some unique to GNU. See the file NEWS for a list of major changes in the current release. See the file INSTALL for compilation and installation instructions. +To verify the GPG signature of the release, you will need the public +key of the findutils maintainer. You can download this from +ftp://ftp.gnu.org/gnu/gnu-keyring.gpg. Alternatively, you could query +a PGP keyserver, but you will need to use one that can cope with +subkeys containing photos. Many older key servers cannot do this. I +use subkeys.pgp.net. I think that one works. See also the +"Downloading" section of http://www.gnu.org/software/findutils/. + Special configure options: --with-afs @@ -21,6 +30,13 @@ getpwuid or getgrgid when needed. Speeds up -nouser and -nogroup unless you are running NIS or Hesiod, which make password and group calls very expensive. +--enable-debug + Produce output on the standard error output indicating what find is +doing. This information includes details about how the command line +has been parsed and what files have been stat()ed. This output is +normally interesting only to the maintainer, and so is off by default. + + To gain speed, GNU find avoids statting files whenever possible. It does this by: 1. Checking the number of links to directories and not statting files @@ -39,9 +55,5 @@ searching has been moved to a separate program, `locate'; the same thing has been done in 4.4BSD. If you use locate, you should run the included `updatedb' script from cron periodically (typically nightly). -The `Makefile.am' files are used by an experimental program called -AutoMake that is under development. It's not ready for general use -yet, so don't worry about them. - Mail suggestions and bug reports for these programs to -bug-gnu-utils@prep.ai.mit.edu. +bug-findutils@gnu.org. diff --git a/src/bin/findutils/config.h b/src/bin/findutils/config.h index 31149417ac..2b8687f6ab 100644 --- a/src/bin/findutils/config.h +++ b/src/bin/findutils/config.h @@ -1,177 +1,1047 @@ -/* config.h. Generated automatically by configure. */ -/* config.h.in. Generated automatically from configure.in by autoheader. */ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.in by autoheader. */ -/* Define if on AIX 3. - System headers sometimes define this. - We just want to avoid a redefinition error message. */ -#ifndef _ALL_SOURCE -/* #undef _ALL_SOURCE */ -#endif +/* Define to the number of bits in type 'ptrdiff_t'. */ +#define BITSIZEOF_PTRDIFF_T 32 -/* Define if using alloca.c. */ -/* #undef C_ALLOCA */ +/* Define to the number of bits in type 'sig_atomic_t'. */ +#define BITSIZEOF_SIG_ATOMIC_T 32 -/* Define if the closedir function returns void instead of int. */ +/* Define to the number of bits in type 'size_t'. */ +#define BITSIZEOF_SIZE_T 32 + +/* Define to the number of bits in type 'wchar_t'. */ +#define BITSIZEOF_WCHAR_T 16 + +/* Define to the number of bits in type 'wint_t'. */ +#define BITSIZEOF_WINT_T 32 + +/* Define if you want find -nouser and -nogroup to make tables of used UIDs + and GIDs at startup instead of using getpwuid or getgrgid when needed. + Speeds up -nouser and -nogroup unless you are running NIS or Hesiod, which + make password and group calls very expensive. */ +/* #undef CACHE_IDS */ + +/* Define if chown is not POSIX compliant regarding IDs of -1. */ +#define CHOWN_FAILS_TO_HONOR_ID_OF_NEGATIVE_ONE 1 + +/* Define if chown modifies symlinks. */ +/* #undef CHOWN_MODIFIES_SYMLINK */ + +/* Define to 1 if the `closedir' function returns void instead of `int'. */ /* #undef CLOSEDIR_VOID */ -/* Define to empty if the keyword does not work. */ -/* #undef const */ - -/* Define to one of _getb67, GETB67, getb67 for Cray-2 and Cray-YMP systems. - This function is required for alloca.c support on those systems. */ +/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP + systems. This function is required for `alloca.c' support on those systems. + */ /* #undef CRAY_STACKSEG_END */ -/* Define to `int' if doesn't define. */ -/* #undef gid_t */ +/* Define to 1 if using `alloca.c'. */ +/* #undef C_ALLOCA */ -/* Define if you have alloca, as a function or macro. */ +/* Define if you want to see find's innards */ +/* #undef DEBUG */ + +/* Define if you want to see a message every time find calls the stat() system + call */ +/* #undef DEBUG_STAT */ + +/* the name of the file descriptor member of DIR */ +/* #undef DIR_FD_MEMBER_NAME */ + +#ifdef DIR_FD_MEMBER_NAME +# define DIR_TO_FD(Dir_p) ((Dir_p)->DIR_FD_MEMBER_NAME) +#else +# define DIR_TO_FD(Dir_p) -1 +#endif + + +/* Define to 1 if // is a file system root distinct from /. */ +/* #undef DOUBLE_SLASH_IS_DISTINCT_ROOT */ + +/* Define if struct dirent has a member d_ino that actually works. */ +#define D_INO_IN_DIRENT 1 + +/* Define to 1 if translation of program messages to the user's native + language is requested. */ +/* #undef ENABLE_NLS */ + +/* Define if gnulib's fchdir() replacement is used. */ +/* #undef FCHDIR_REPLACEMENT */ + +/* Define on systems for which file names may have a so-called `drive letter' + prefix, define this to compute the length of that prefix, including the + colon. */ +#define FILE_SYSTEM_ACCEPTS_DRIVE_LETTER_PREFIX 0 + +/* Define if the backslash character may also serve as a file name component + separator. */ +#define FILE_SYSTEM_BACKSLASH_IS_FILE_NAME_SEPARATOR 0 + +/* Define if a drive letter prefix denotes a relative path if it is not + followed by a file name component separator. */ +#define FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE 0 + +/* Define if we are compiling GNU findutils */ +#define FINDUTILS 1 + +/* Define to nothing if C supports flexible array members, and to 1 if it does + not. That way, with a declaration like `struct s { int n; double + d[FLEXIBLE_ARRAY_MEMBER]; };', the struct hack can be used with pre-C99 + compilers. When computing the size of such an object, don't use 'sizeof + (struct s)' as it overestimates the size. Use 'offsetof (struct s, d)' + instead. Don't use 'offsetof (struct s, d[0])', as this doesn't work with + MSVC and with C++ compilers. */ +#define FLEXIBLE_ARRAY_MEMBER 1 + +/* Define to make the limit macros in visible. */ +#define GL_TRIGGER_STDC_LIMIT_MACROS 1 + +/* Define to 1 when using the gnulib module canonicalize. */ +#define GNULIB_CANONICALIZE 1 + +/* Define to 1 when using the gnulib module close-stream. */ +#define GNULIB_CLOSE_STREAM 1 + +/* Define to 1 when using the gnulib module fcntl-safer. */ +#define GNULIB_FCNTL_SAFER 1 + +/* Define to 1 when using the gnulib module fopen-safer. */ +#define GNULIB_FOPEN_SAFER 1 + +/* Define to indicate the 'malloc' module. */ +#define GNULIB_MALLOC_GNU 1 + +/* Define to indicate the 'realloc' module. */ +#define GNULIB_REALLOC_GNU 1 + +/* Define to 1 if you have the `alarm' function. */ +#define HAVE_ALARM 1 + +/* Define to 1 if you have 'alloca' after including , a header that + may be supplied by this distribution. */ #define HAVE_ALLOCA 1 -/* Define if you have and it should be used (not on Ultrix). */ +/* Define HAVE_ALLOCA_H for backward compatibility with older code that + includes only if HAVE_ALLOCA_H is defined. */ #define HAVE_ALLOCA_H 1 -/* Define if you don't have vprintf but do have _doprnt. */ +/* Define to 1 if you have the `btowc' function. */ +#define HAVE_BTOWC 1 + +/* Define to 1 if you have the `canonicalize_file_name' function. */ +/* #undef HAVE_CANONICALIZE_FILE_NAME */ + +/* Define to 1 if you have the MacOS X function CFLocaleCopyCurrent in the + CoreFoundation framework. */ +/* #undef HAVE_CFLOCALECOPYCURRENT */ + +/* Define to 1 if you have the MacOS X function CFPreferencesCopyAppValue in + the CoreFoundation framework. */ +/* #undef HAVE_CFPREFERENCESCOPYAPPVALUE */ + +/* Define to 1 if your system has a working `chown' function. */ +/* #undef HAVE_CHOWN */ + +/* Define if the GNU dcgettext() function is already present or preinstalled. + */ +/* #undef HAVE_DCGETTEXT */ + +/* Define to 1 if you have the declaration of `canonicalize_file_name', and to + 0 if you don't. */ +#define HAVE_DECL_CANONICALIZE_FILE_NAME 0 + +/* Define to 1 if you have the declaration of `dirfd', and to 0 if you don't. + */ +#define HAVE_DECL_DIRFD 1 + +/* Define to 1 if you have the declaration of `fpurge', and to 0 if you don't. + */ +#define HAVE_DECL_FPURGE 1 + +/* Define to 1 if you have the declaration of `getcwd', and to 0 if you don't. + */ +#define HAVE_DECL_GETCWD 1 + +/* Define to 1 if you have the declaration of `getc_unlocked', and to 0 if you + don't. */ +#define HAVE_DECL_GETC_UNLOCKED 1 + +/* Define to 1 if you have the declaration of `getdelim', and to 0 if you + don't. */ +#define HAVE_DECL_GETDELIM 0 + +/* Define to 1 if you have the declaration of `getenv', and to 0 if you don't. + */ +#define HAVE_DECL_GETENV 1 + +/* Define to 1 if you have the declaration of `getline', and to 0 if you + don't. */ +#define HAVE_DECL_GETLINE 0 + +/* Define to 1 if you have the declaration of `imaxabs', and to 0 if you + don't. */ +#define HAVE_DECL_IMAXABS 1 + +/* Define to 1 if you have the declaration of `imaxdiv', and to 0 if you + don't. */ +#define HAVE_DECL_IMAXDIV 1 + +/* Define to 1 if you have the declaration of `isblank', and to 0 if you + don't. */ +#define HAVE_DECL_ISBLANK 1 + +/* Define to 1 if you have the declaration of `memrchr', and to 0 if you + don't. */ +#define HAVE_DECL_MEMRCHR 0 + +/* Define to 1 if you have the declaration of `mkdir', and to 0 if you don't. + */ +#define HAVE_DECL_MKDIR 1 + +/* Define to 1 if you have the declaration of `strdup', and to 0 if you don't. + */ +#define HAVE_DECL_STRDUP 1 + +/* Define to 1 if you have the declaration of `strerror', and to 0 if you + don't. */ +/* #undef HAVE_DECL_STRERROR */ + +/* Define to 1 if you have the declaration of `strerror_r', and to 0 if you + don't. */ +#define HAVE_DECL_STRERROR_R 1 + +/* Define to 1 if you have the declaration of `strmode', and to 0 if you + don't. */ +#define HAVE_DECL_STRMODE 0 + +/* Define to 1 if you have the declaration of `strndup', and to 0 if you + don't. */ +#define HAVE_DECL_STRNDUP 0 + +/* Define to 1 if you have the declaration of `strnlen', and to 0 if you + don't. */ +#define HAVE_DECL_STRNLEN 1 + +/* Define to 1 if you have the declaration of `strtoimax', and to 0 if you + don't. */ +#define HAVE_DECL_STRTOIMAX 1 + +/* Define to 1 if you have the declaration of `strtoll', and to 0 if you + don't. */ +/* #undef HAVE_DECL_STRTOLL */ + +/* Define to 1 if you have the declaration of `strtoull', and to 0 if you + don't. */ +/* #undef HAVE_DECL_STRTOULL */ + +/* Define to 1 if you have the declaration of `strtoumax', and to 0 if you + don't. */ +#define HAVE_DECL_STRTOUMAX 1 + +/* Define to 1 if you have the declaration of `tzname', and to 0 if you don't. + */ +/* #undef HAVE_DECL_TZNAME */ + +/* Define to 1 if you have the declaration of `__fpending', and to 0 if you + don't. */ +#define HAVE_DECL___FPENDING 0 + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +#define HAVE_DIRENT_H 1 + +/* Define to 1 if you have the `dirfd' function. */ +#define HAVE_DIRFD 1 + +/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */ /* #undef HAVE_DOPRNT */ -/* Define if you have the getmntent function. */ +/* Define to 1 if you have the `dup2' function. */ +#define HAVE_DUP2 1 + +/* Define to 1 if you have the `endgrent' function. */ +#define HAVE_ENDGRENT 1 + +/* Define to 1 if you have the `endmntent' function. */ +/* #undef HAVE_ENDMNTENT */ + +/* Define to 1 if you have the `endpwent' function. */ +#define HAVE_ENDPWENT 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_ERRNO_H 1 + +/* Define to 1 if you have the `fchdir' function. */ +#define HAVE_FCHDIR 1 + +/* Define to 1 if you have the `fchmodat' function. */ +/* #undef HAVE_FCHMODAT */ + +/* Define to 1 if you have the header file. */ +#define HAVE_FCNTL_H 1 + +/* Define to 1 if you have the `fdopendir' function. */ +/* #undef HAVE_FDOPENDIR */ + +/* Define to 1 if you have the `flockfile' function. */ +/* #undef HAVE_FLOCKFILE */ + +/* Define to 1 if you have the `forcefindlib' function. */ +/* #undef HAVE_FORCEFINDLIB */ + +/* Define to 1 if you have the `fpurge' function. */ +#define HAVE_FPURGE 1 + +/* Define to 1 if fseeko (and presumably ftello) exists and is declared. */ +#define HAVE_FSEEKO 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_FS_INFO_H 1 + +/* Define to 1 if you have the `fs_stat_dev' function. */ +#define HAVE_FS_STAT_DEV 1 + +/* Define to 1 if you have the `funlockfile' function. */ +/* #undef HAVE_FUNLOCKFILE */ + +/* Define to 1 if you have the `getcwd' function. */ +#define HAVE_GETCWD 1 + +/* Define to 1 if you have the `getdelim' function. */ +#define HAVE_GETDELIM 1 + +/* Define to 1 if you have the `getmntent' function. */ /* #undef HAVE_GETMNTENT */ -/* Define if your struct stat has st_blocks. */ -/* #undef HAVE_ST_BLOCKS */ +/* Define to 1 if you have the `getmntinfo' function. */ +/* #undef HAVE_GETMNTINFO */ -/* Define if your struct stat has st_rdev. */ -#define HAVE_ST_RDEV 1 +/* Define to 1 if you have the header file. */ +#define HAVE_GETOPT_H 1 -/* Define if you have the strftime function. */ +/* Define to 1 if you have the `getopt_long_only' function. */ +#define HAVE_GETOPT_LONG_ONLY 1 + +/* Define to 1 if you have the `getpagesize' function. */ +#define HAVE_GETPAGESIZE 1 + +/* Define if the GNU gettext() function is already present or preinstalled. */ +/* #undef HAVE_GETTEXT */ + +/* Define to 1 if you have the `hasmntopt' function. */ +/* #undef HAVE_HASMNTOPT */ + +/* Define if you have the iconv() function and it works. */ +#define HAVE_ICONV 1 + +/* Define if your compiler supports the #include_next directive. */ +#define HAVE_INCLUDE_NEXT 1 + +/* Define to 1 if the compiler supports one of the keywords 'inline', + '__inline__', '__inline' and effectively inlines functions marked as such. + */ +#define HAVE_INLINE 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_IO_H */ + +/* Define to 1 if you have the `isblank' function. */ +#define HAVE_ISBLANK 1 + +/* Define to 1 if you have the `iswcntrl' function. */ +#define HAVE_ISWCNTRL 1 + +/* Define to 1 if you have the `iswctype' function. */ +#define HAVE_ISWCTYPE 1 + +/* Define if you have and nl_langinfo(CODESET). */ +/* #undef HAVE_LANGINFO_CODESET */ + +/* Define to 1 if you have the `lchmod' function. */ +/* #undef HAVE_LCHMOD */ + +/* Define to 1 if you have the `lchown' function. */ +#define HAVE_LCHOWN 1 + +/* Define to 1 if you have the `sun' library (-lsun). */ +/* #undef HAVE_LIBSUN */ + +/* Define to 1 if you have the header file. */ +#define HAVE_LIMITS_H 1 + +/* Define to 1 if you have the `listmntent' function. */ +/* #undef HAVE_LISTMNTENT */ + +/* Define to 1 if you have the header file. */ +#define HAVE_LOCALE_H 1 + +/* Define to 1 if you support file names longer than 14 characters. */ +#define HAVE_LONG_FILE_NAMES 1 + +/* Define to 1 if the system has the type `long long int'. */ +#define HAVE_LONG_LONG_INT 1 + +/* Define to 1 if you have the `lstat' function. */ +#define HAVE_LSTAT 1 + +/* Define to 1 if your system has a GNU libc compatible `malloc' function, and + to 0 otherwise. */ +#define HAVE_MALLOC 1 + +/* Define if the 'malloc' function is POSIX compliant. */ +#define HAVE_MALLOC_POSIX 1 + +/* Define to 1 if you have the `mblen' function. */ +#define HAVE_MBLEN 1 + +/* Define to 1 if you have the `mbrlen' function. */ +#define HAVE_MBRLEN 1 + +/* Define to 1 if you have the `mbrtowc' function. */ +#define HAVE_MBRTOWC 1 + +/* Define to 1 if you have the `mbsinit' function. */ +#define HAVE_MBSINIT 1 + +/* Define to 1 if you have the `mbsrtowcs' function. */ +#define HAVE_MBSRTOWCS 1 + +/* Define to 1 if declares mbstate_t. */ +#define HAVE_MBSTATE_T 1 + +/* Define to 1 if you have the `memcmp' function. */ +#define HAVE_MEMCMP 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the `mempcpy' function. */ +/* #undef HAVE_MEMPCPY */ + +/* Define to 1 if you have the `memrchr' function. */ +#define HAVE_MEMRCHR 1 + +/* Define to 1 if you have the `memset' function. */ +#define HAVE_MEMSET 1 + +/* Define to 1 if you have the `mkdirat' function. */ +/* #undef HAVE_MKDIRAT */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_MNTENT_H */ + +/* Define to 1 if you have the header file, and it defines `DIR'. */ +/* #undef HAVE_NDIR_H */ + +/* Define to 1 if you have the `next_dev' function. */ +#define HAVE_NEXT_DEV 1 + +/* Define to 1 if you have the `openat' function. */ +/* #undef HAVE_OPENAT */ + +/* Define to 1 if getcwd works, except it sometimes fails when it shouldn't, + setting errno to ERANGE, ENAMETOOLONG, or ENOENT. If __GETCWD_PREFIX is not + defined, it doesn't matter whether HAVE_PARTLY_WORKING_GETCWD is defined. + */ +/* #undef HAVE_PARTLY_WORKING_GETCWD */ + +/* Define to 1 if you have the `pathconf' function. */ +#define HAVE_PATHCONF 1 + +/* Define to 1 if you have the `pipe' function. */ +#define HAVE_PIPE 1 + +/* Define to 1 if you have the `readlink' function. */ +#define HAVE_READLINK 1 + +/* Define to 1 if your system has a GNU libc compatible `realloc' function, + and to 0 otherwise. */ +#define HAVE_REALLOC 1 + +/* Define if the 'realloc' function is POSIX compliant. */ +#define HAVE_REALLOC_POSIX 1 + +/* Define to 1 if you have the `resolvepath' function. */ +/* #undef HAVE_RESOLVEPATH */ + +/* Define to 1 if you have the `rpmatch' function. */ +/* #undef HAVE_RPMATCH */ + +/* Define to 1 if you have the `setlocale' function. */ +#define HAVE_SETLOCALE 1 + +/* Define to 1 if you have the `setmntent' function. */ +/* #undef HAVE_SETMNTENT */ + +/* Define to 1 if 'sig_atomic_t' is a signed integer type. */ +#define HAVE_SIGNED_SIG_ATOMIC_T 1 + +/* Define to 1 if 'wchar_t' is a signed integer type. */ +/* #undef HAVE_SIGNED_WCHAR_T */ + +/* Define to 1 if 'wint_t' is a signed integer type. */ +/* #undef HAVE_SIGNED_WINT_T */ + +/* Define to 1 if stdbool.h conforms to C99. */ +/* #undef HAVE_STDBOOL_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_STDDEF_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDIO_EXT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDIO_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the `stpcpy' function. */ +#define HAVE_STPCPY 1 + +/* Define to 1 if you have the `strdup' function. */ +#define HAVE_STRDUP 1 + +/* Define to 1 if you have the `strerror' function. */ +#define HAVE_STRERROR 1 + +/* Define to 1 if you have the `strerror_r' function. */ +#define HAVE_STRERROR_R 1 + +/* Define to 1 if you have the `strftime' function. */ #define HAVE_STRFTIME 1 -/* Define if you have that is POSIX.1 compatible. */ +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define if you have the strndup() function and it works. */ +/* #undef HAVE_STRNDUP */ + +/* Define to 1 if you have the `strspn' function. */ +#define HAVE_STRSPN 1 + +/* Define to 1 if you have the `strstr' function. */ +#define HAVE_STRSTR 1 + +/* Define to 1 if you have the `strtoimax' function. */ +#define HAVE_STRTOIMAX 1 + +/* Define to 1 if you have the `strtol' function. */ +#define HAVE_STRTOL 1 + +/* Define to 1 if you have the `strtoll' function. */ +#define HAVE_STRTOLL 1 + +/* Define to 1 if you have the `strtoul' function. */ +#define HAVE_STRTOUL 1 + +/* Define to 1 if you have the `strtoull' function. */ +#define HAVE_STRTOULL 1 + +/* Define to 1 if you have the `strtoumax' function. */ +#define HAVE_STRTOUMAX 1 + +/* Define to 1 if your 'struct dirent' has a d_type member */ +/* #undef HAVE_STRUCT_DIRENT_D_TYPE */ + +/* Define to 1 if `f_fstypename' is member of `struct fsstat'. */ +/* #undef HAVE_STRUCT_FSSTAT_F_FSTYPENAME */ + +/* Define to 1 if `f_fstypename' is member of `struct statfs'. */ +/* #undef HAVE_STRUCT_STATFS_F_FSTYPENAME */ + +/* Define to 1 if `st_blocks' is member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_BLOCKS 1 + +/* Define to 1 if `st_rdev' is member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_RDEV 1 + +/* Define to 1 if `tm_zone' is member of `struct tm'. */ +#define HAVE_STRUCT_TM_TM_ZONE 1 + +/* Define to 1 if your `struct stat' has `st_blocks'. Deprecated, use + `HAVE_STRUCT_STAT_ST_BLOCKS' instead. */ +#define HAVE_ST_BLOCKS 1 + +/* Define if struct stat has an st_dm_mode member. */ +/* #undef HAVE_ST_DM_MODE */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_BITYPES_H */ + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +/* #undef HAVE_SYS_DIR_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_FS_TYPES_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_INTTYPES_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_MKDEV_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_MNTENT_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_MNTIO_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_MNTTAB_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_MOUNT_H */ + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +/* #undef HAVE_SYS_NDIR_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_PARAM_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STATVFS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TIME_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_UCRED_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_UTSNAME_H 1 + +/* Define to 1 if you have that is POSIX.1 compatible. */ #define HAVE_SYS_WAIT_H 1 -/* Define if your struct tm has tm_zone. */ +/* Define to 1 if you have the header file. */ +#define HAVE_TIME_H 1 + +/* Define if struct tm has the tm_gmtoff member. */ +#define HAVE_TM_GMTOFF 1 + +/* Define to 1 if your `struct tm' has `tm_zone'. Deprecated, use + `HAVE_STRUCT_TM_TM_ZONE' instead. */ #define HAVE_TM_ZONE 1 -/* Define if you don't have tm_zone but do have the external array - tzname. */ +/* Define to 1 if you don't have `tm_zone' but do have the external array + `tzname'. */ /* #undef HAVE_TZNAME */ -/* Define if you have the vprintf function. */ +/* Define to 1 if you have the `tzset' function. */ +#define HAVE_TZSET 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if the system has the type `unsigned long long int'. */ +#define HAVE_UNSIGNED_LONG_LONG_INT 1 + +/* Define to 1 if you have the `vprintf' function. */ #define HAVE_VPRINTF 1 -/* Define if major, minor, and makedev are declared in . */ +/* Define to 1 if you have the `waitpid' function. */ +#define HAVE_WAITPID 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_WCHAR_H 1 + +/* Define if you have the 'wchar_t' type. */ +#define HAVE_WCHAR_T 1 + +/* Define to 1 if you have the `wcrtomb' function. */ +#define HAVE_WCRTOMB 1 + +/* Define to 1 if you have the `wcscoll' function. */ +#define HAVE_WCSCOLL 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_WCTYPE_H 1 + +/* Define if you have the 'wint_t' type. */ +#define HAVE_WINT_T 1 + +/* Define to 1 if you have the `wmemchr' function. */ +#define HAVE_WMEMCHR 1 + +/* Define to 1 if you have the `wmemcpy' function. */ +#define HAVE_WMEMCPY 1 + +/* Define to 1 if you have the `wmempcpy' function. */ +#define HAVE_WMEMPCPY 1 + +/* Define to 1 if O_NOATIME works. */ +#define HAVE_WORKING_O_NOATIME 0 + +/* Define to 1 if O_NOFOLLOW works. */ +#define HAVE_WORKING_O_NOFOLLOW 0 + +/* Define to 1 if the system has the type `_Bool'. */ +/* #undef HAVE__BOOL */ + +/* Define to 1 if you have the `__fpending' function. */ +/* #undef HAVE___FPENDING */ + +/* Define to 1 if you have the `__fpurge' function. */ +#define HAVE___FPURGE 1 + +/* Define to 1 if you have the `__freading' function. */ +#define HAVE___FREADING 1 + +#if FILE_SYSTEM_BACKSLASH_IS_FILE_NAME_SEPARATOR +# define ISSLASH(C) ((C) == '/' || (C) == '\\') +#else +# define ISSLASH(C) ((C) == '/') +#endif + +/* Define if you want to use the leaf optimisation (this can still be turned + off with -noleaf) */ +#define LEAF_OPTIMISATION 1 + +/* Define to 1 if lseek does not detect pipes. */ +/* #undef LSEEK_PIPE_BROKEN */ + +/* Define to 1 if `lstat' dereferences a symlink specified with a trailing + slash. */ +/* #undef LSTAT_FOLLOWS_SLASHED_SYMLINK */ + +/* Define to 1 if `major', `minor', and `makedev' are declared in . + */ /* #undef MAJOR_IN_MKDEV */ -/* Define if major, minor, and makedev are declared in . */ +/* Define to 1 if `major', `minor', and `makedev' are declared in + . */ /* #undef MAJOR_IN_SYSMACROS */ -/* Define if on MINIX. */ -/* #undef _MINIX */ +/* If malloc(0) is != NULL, define this to 1. Otherwise define this to 0. */ +#define MALLOC_0_IS_NONNULL 1 -/* Define to `int' if doesn't define. */ -/* #undef pid_t */ +/* Define if there is no specific function for reading the list of mounted + file systems. fread will be used to read /etc/mnttab. (SVR2) */ +/* #undef MOUNTED_FREAD */ -/* Define if the system does not provide POSIX.1 features except - with this defined. */ -/* #undef _POSIX_1_SOURCE */ +/* Define if (like SVR2) there is no specific function for reading the list of + mounted file systems, and your system has these header files: + and . (SVR3) */ +/* #undef MOUNTED_FREAD_FSTYP */ -/* Define if you need to in order for stat and other things to work. */ -/* #undef _POSIX_SOURCE */ +/* Define if there are functions named next_dev and fs_stat_dev for reading + the list of mounted file systems. (BeOS) */ +#define MOUNTED_FS_STAT_DEV 1 -/* Define to `unsigned' if doesn't define. */ -/* #undef size_t */ +/* Define if there is a function named getfsstat for reading the list of + mounted file systems. (DEC Alpha running OSF/1) */ +/* #undef MOUNTED_GETFSSTAT */ + +/* Define if there is a function named getmnt for reading the list of mounted + file systems. (Ultrix) */ +/* #undef MOUNTED_GETMNT */ + +/* Define if there is a function named getmntent for reading the list of + mounted file systems, and that function takes a single argument. (4.3BSD, + SunOS, HP-UX, Dynix, Irix) */ +/* #undef MOUNTED_GETMNTENT1 */ + +/* Define if there is a function named getmntent for reading the list of + mounted file systems, and that function takes two arguments. (SVR4) */ +/* #undef MOUNTED_GETMNTENT2 */ + +/* Define if there is a function named getmntinfo for reading the list of + mounted file systems and it returns an array of 'struct statfs'. (4.4BSD, + Darwin) */ +/* #undef MOUNTED_GETMNTINFO */ + +/* Define if there is a function named getmntinfo for reading the list of + mounted file systems and it returns an array of 'struct statvfs'. (NetBSD + 3.0) */ +/* #undef MOUNTED_GETMNTINFO2 */ + +/* Define if there is a function named listmntent that can be used to list all + mounted file systems. (UNICOS) */ +/* #undef MOUNTED_LISTMNTENT */ + +/* Define if there is a function named mntctl that can be used to read the + list of mounted file systems, and there is a system header file that + declares `struct vmount.' (AIX) */ +/* #undef MOUNTED_VMOUNT */ + +/* Name of package */ +#define PACKAGE "findutils" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "bug-findutils@gnu.org" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "GNU findutils" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "GNU findutils 4.2.33" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "findutils" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "4.2.33" + +/* the number of pending output bytes on stream `fp' */ +#define PENDING_OUTPUT_N_BYTES fp->_IO_write_ptr - fp->_IO_write_base + +/* Define if exists and defines unusable PRI* macros. */ +/* #undef PRI_MACROS_BROKEN */ + +/* Define to 1 if the C compiler supports function prototypes. */ +#define PROTOTYPES 1 + +/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type + 'ptrdiff_t'. */ +#define PTRDIFF_T_SUFFIX l + +/* Define this to 1 if strerror is broken. */ +/* #undef REPLACE_STRERROR */ + +/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type + 'sig_atomic_t'. */ +#define SIG_ATOMIC_T_SUFFIX + +/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type + 'size_t'. */ +#define SIZE_T_SUFFIX ul /* If using the C implementation of alloca, define if you know the direction of stack growth for your system; otherwise it will be - automatically deduced at run-time. + automatically deduced at runtime. STACK_DIRECTION > 0 => grows toward higher addresses STACK_DIRECTION < 0 => grows toward lower addresses - STACK_DIRECTION = 0 => direction of growth unknown - */ + STACK_DIRECTION = 0 => direction of growth unknown */ /* #undef STACK_DIRECTION */ -/* Define if the `S_IS*' macros in do not work properly. */ +/* Define to 1 if the `S_IS*' macros in do not work properly. */ /* #undef STAT_MACROS_BROKEN */ -/* Define if you have the ANSI C header files. */ +/* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 -/* Define if your declares struct tm. */ +/* Define to 1 if strerror_r returns char *. */ +/* #undef STRERROR_R_CHAR_P */ + +/* Define to 1 if your declares `struct tm'. */ /* #undef TM_IN_SYS_TIME */ -/* Define to `int' if doesn't define. */ -/* #undef uid_t */ +/* Defined if you specify --enable-d_type-optimisation to configure. */ +#define USE_STRUCT_DIRENT_D_TYPE 1 -/* Define if you have the Andrew File System. */ -/* #undef AFS */ +/* Version number of package */ +#define VERSION "4.2.33" -/* Define If you want find -nouser and -nogroup to make tables of - used UIDs and GIDs at startup instead of using getpwuid or - getgrgid when needed. Speeds up -nouser and -nogroup unless you - are running NIS or Hesiod, which make password and group calls - very expensive. */ -/* #undef CACHE_IDS */ +/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type + 'wchar_t'. */ +#define WCHAR_T_SUFFIX -/* Define to use SVR4 statvfs to get filesystem type. */ -/* #undef FSTYPE_STATVFS */ +/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type + 'wint_t'. */ +#define WINT_T_SUFFIX u -/* Define to use SVR3.2 statfs to get filesystem type. */ -/* #undef FSTYPE_USG_STATFS */ +/* Number of bits in a file offset, on hosts where this is settable. */ +/* #undef _FILE_OFFSET_BITS */ -/* Define to use AIX3 statfs to get filesystem type. */ -/* #undef FSTYPE_AIX_STATFS */ +/* Enable GNU extensions on systems that have them. */ +#ifndef _GNU_SOURCE +# define _GNU_SOURCE 1 +#endif -/* Define to use 4.3BSD getmntent to get filesystem type. */ -/* #undef FSTYPE_MNTENT */ +/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */ +/* #undef _LARGEFILE_SOURCE */ -/* Define to use 4.4BSD and OSF1 statfs to get filesystem type. */ -/* #undef FSTYPE_STATFS */ +/* Define for large files, on AIX-style hosts. */ +/* #undef _LARGE_FILES */ -/* Define to use Ultrix getmnt to get filesystem type. */ -/* #undef FSTYPE_GETMNT */ +/* Define to 1 if on MINIX. */ +/* #undef _MINIX */ -/* Define to `unsigned long' if doesn't define. */ +/* Define to 2 if the system does not provide POSIX.1 features except with + this defined. */ +/* #undef _POSIX_1_SOURCE */ + +/* Define to 1 if you need to in order for `stat' and other things to work. */ +/* #undef _POSIX_SOURCE */ + +/* Define if you want regoff_t to be at least as wide POSIX requires. */ +#define _REGEX_LARGE_OFFSETS 1 + +/* Enable extensions on AIX 3, Interix. */ +#ifndef _ALL_SOURCE +# define _ALL_SOURCE 1 +#endif +/* Enable GNU extensions on systems that have them. */ +#ifndef _GNU_SOURCE +# define _GNU_SOURCE 1 +#endif +/* Enable threading extensions on Solaris. */ +#ifndef _POSIX_PTHREAD_SEMANTICS +# define _POSIX_PTHREAD_SEMANTICS 1 +#endif +/* Enable extensions on HP NonStop. */ +#ifndef _TANDEM_SOURCE +# define _TANDEM_SOURCE 1 +#endif +/* Enable general extensions on Solaris. */ +#ifndef __EXTENSIONS__ +# define __EXTENSIONS__ 1 +#endif + + +/* Define to rpl_ if the getopt replacement functions and variables should be + used. */ +/* #undef __GETOPT_PREFIX */ + +/* Define to rpl_ if the openat replacement function should be used. */ +#define __OPENAT_PREFIX rpl_ + +/* Define like PROTOTYPES; this can be used by system headers. */ +#define __PROTOTYPES 1 + +/* Ensure that defines the limit macros, since gnulib's + relies on them. */ +#if defined __cplusplus && !defined __STDC_LIMIT_MACROS && GL_TRIGGER_STDC_LIMIT_MACROS +# define __STDC_LIMIT_MACROS 1 +#endif + + +/* Define to `unsigned long' if does not define. */ /* #undef dev_t */ -/* Define to `unsigned long' if doesn't define. */ +/* Define to rpl_fchownat if the replacement function should be used. */ +#define fchownat rpl_fchownat + +/* Define to a replacement function name for fnmatch(). */ +#define fnmatch gnu_fnmatch + +/* Define to `int' if doesn't define. */ +/* #undef gid_t */ + +/* Define to `__inline__' or `__inline' if that's what the C compiler + calls it, or to nothing if 'inline' is not supported under any name. */ +#ifndef __cplusplus +/* #undef inline */ +#endif + +/* Define to `unsigned long' if does not define. */ /* #undef ino_t */ -/* Define if you have the fchdir function. */ -#ifndef B_BEOS_VERSION -#include -#endif -#if B_BEOS_VERSION > B_BEOS_VERSION_5 -#define HAVE_FCHDIR 1 +/* Define to rpl_malloc if the replacement function should be used. */ +/* #undef malloc */ + +/* Define to a type if does not define. */ +/* #undef mbstate_t */ + +/* Define to rpl_memcmp if the replacement function should be used. */ +/* #undef memcmp */ + +/* Define to rpl_mktime if the replacement function should be used. */ +/* #undef mktime */ + +/* Define to `int' if does not define. */ +/* #undef mode_t */ + +/* Define to the name of the strftime replacement function. */ +#define my_strftime nstrftime + +/* Define to `int' if does not define. */ +/* #undef pid_t */ + +/* Define to rpl_re_comp if the replacement should be used. */ +#define re_comp rpl_re_comp + +/* Define to rpl_re_compile_fastmap if the replacement should be used. */ +#define re_compile_fastmap rpl_re_compile_fastmap + +/* Define to rpl_re_compile_pattern if the replacement should be used. */ +#define re_compile_pattern rpl_re_compile_pattern + +/* Define to rpl_re_exec if the replacement should be used. */ +#define re_exec rpl_re_exec + +/* Define to rpl_re_match if the replacement should be used. */ +#define re_match rpl_re_match + +/* Define to rpl_re_match_2 if the replacement should be used. */ +#define re_match_2 rpl_re_match_2 + +/* Define to rpl_re_search if the replacement should be used. */ +#define re_search rpl_re_search + +/* Define to rpl_re_search_2 if the replacement should be used. */ +#define re_search_2 rpl_re_search_2 + +/* Define to rpl_re_set_registers if the replacement should be used. */ +#define re_set_registers rpl_re_set_registers + +/* Define to rpl_re_set_syntax if the replacement should be used. */ +#define re_set_syntax rpl_re_set_syntax + +/* Define to rpl_re_syntax_options if the replacement should be used. */ +#define re_syntax_options rpl_re_syntax_options + +/* Define to rpl_realloc if the replacement function should be used. */ +/* #undef realloc */ + +/* Define to a replacement function name for realpath(). */ +#define realpath rpl_realpath + +/* Define to rpl_regcomp if the replacement should be used. */ +#define regcomp rpl_regcomp + +/* Define to rpl_regerror if the replacement should be used. */ +#define regerror rpl_regerror + +/* Define to rpl_regexec if the replacement should be used. */ +#define regexec rpl_regexec + +/* Define to rpl_regfree if the replacement should be used. */ +#define regfree rpl_regfree + +/* Define to the equivalent of the C99 'restrict' keyword, or to + nothing if this is not supported. Do not define if restrict is + supported directly. */ +#define restrict __restrict +/* Work around a bug in Sun C++: it does not support _Restrict, even + though the corresponding Sun C compiler does, which causes + "#define restrict _Restrict" in the previous line. Perhaps some future + version of Sun C++ will work with _Restrict; if so, it'll probably + define __RESTRICT, just as Sun C does. */ +#if defined __SUNPRO_CC && !defined __RESTRICT +# define _Restrict #endif -/* Define if you have the getcwd function. */ -#define HAVE_GETCWD 1 +/* Define to `unsigned int' if does not define. */ +/* #undef size_t */ -/* Define if you have the strerror function. */ -#define HAVE_STRERROR 1 +/* Define to `int' if does not define. */ +/* #undef ssize_t */ -/* Define if you have the header file. */ -#define HAVE_DIRENT_H 1 +/* Define to rpl_strnlen if the replacement function should be used. */ +/* #undef strnlen */ -/* Define if you have the header file. */ -#define HAVE_FCNTL_H 1 +/* Define to `int' if doesn't define. */ +/* #undef uid_t */ -/* Define if you have the header file. */ -#define HAVE_LIMITS_H 1 - -/* Define if you have the header file. */ -/* #undef HAVE_NDIR_H */ - -/* Define if you have the header file. */ -#define HAVE_STRING_H 1 - -/* Define if you have the header file. */ -/* #undef HAVE_SYS_DIR_H */ - -/* Define if you have the header file. */ -/* #undef HAVE_SYS_NDIR_H */ - -/* Define if you have the header file. */ -#define HAVE_UNISTD_H 1 - -/* Define if you have the sun library (-lsun). */ -/* #undef HAVE_LIBSUN */ +#define _IO_ferror_unlocked _IO_ferror_unlocked diff --git a/src/bin/findutils/find/Jamfile b/src/bin/findutils/find/Jamfile index 0b42e1c4b9..8f570f91b5 100644 --- a/src/bin/findutils/find/Jamfile +++ b/src/bin/findutils/find/Jamfile @@ -1,5 +1,6 @@ SubDir HAIKU_TOP src bin findutils find ; +SubDirSysHdrs [ FDirName $(SUBDIR) $(DOTDOT) gnulib lib ] ; SubDirSysHdrs [ FDirName $(SUBDIR) $(DOTDOT) lib ] ; SubDirSysHdrs [ FDirName $(SUBDIR) $(DOTDOT) ] ; @@ -19,6 +20,6 @@ BinCommand find : pred.c tree.c util.c - : libfindutils.a : findutils.rdef ; + : libfindutils.a gnulibfindutils.a : findutils.rdef ; SEARCH on [ FGristFiles findutils.rdef ] = [ FDirName $(SUBDIR) $(DOTDOT) ] ; diff --git a/src/bin/findutils/find/defs.h b/src/bin/findutils/find/defs.h index ec029de1d1..02d3650b88 100644 --- a/src/bin/findutils/find/defs.h +++ b/src/bin/findutils/find/defs.h @@ -1,19 +1,28 @@ /* defs.h -- data types and declarations. - Copyright (C) 1990, 91, 92, 93, 94 Free Software Foundation, Inc. + Copyright (C) 1990, 91, 92, 93, 94, 2000, 2001, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ + + +#ifndef INC_DEFS_H +#define INC_DEFS_H 1 + +#include +#include +#include +#include #if defined(HAVE_STRING_H) || defined(STDC_HEADERS) #include @@ -36,27 +45,106 @@ extern int errno; #include #endif -#ifdef HAVE_UNISTD_H +/* The presence of unistd.h is assumed by gnulib these days, so we + * might as well assume it too. + */ #include -#endif #include -#include "regex.h" - -#if __STDC__ -# define P_(s) s -#else -# define P_(s) () +#if HAVE_LIMITS_H +# include +#endif +#ifndef CHAR_BIT +# define CHAR_BIT 8 #endif +#if HAVE_INTTYPES_H +# include +#endif + +#include "regex.h" + +#ifndef S_IFLNK +#define lstat stat +#endif + +# ifndef PARAMS +# if defined PROTOTYPES || (defined __STDC__ && __STDC__) +# define PARAMS(Args) Args +# else +# define PARAMS(Args) () +# endif +# endif + +int lstat PARAMS((const char *__path, struct stat *__statbuf)); +int stat PARAMS((const char *__path, struct stat *__statbuf)); + +int optionl_stat PARAMS((const char *name, struct stat *p)); +int optionp_stat PARAMS((const char *name, struct stat *p)); +int optionh_stat PARAMS((const char *name, struct stat *p)); + +int get_statinfo PARAMS((const char *pathname, const char *name, struct stat *p)); + + + +#ifndef S_ISUID +# define S_ISUID 0004000 +#endif +#ifndef S_ISGID +# define S_ISGID 0002000 +#endif +#ifndef S_ISVTX +# define S_ISVTX 0001000 +#endif +#ifndef S_IRUSR +# define S_IRUSR 0000400 +#endif +#ifndef S_IWUSR +# define S_IWUSR 0000200 +#endif +#ifndef S_IXUSR +# define S_IXUSR 0000100 +#endif +#ifndef S_IRGRP +# define S_IRGRP 0000040 +#endif +#ifndef S_IWGRP +# define S_IWGRP 0000020 +#endif +#ifndef S_IXGRP +# define S_IXGRP 0000010 +#endif +#ifndef S_IROTH +# define S_IROTH 0000004 +#endif +#ifndef S_IWOTH +# define S_IWOTH 0000002 +#endif +#ifndef S_IXOTH +# define S_IXOTH 0000001 +#endif + +#define MODE_WXUSR (S_IWUSR | S_IXUSR) +#define MODE_R (S_IRUSR | S_IRGRP | S_IROTH) +#define MODE_RW (S_IWUSR | S_IWGRP | S_IWOTH | MODE_R) +#define MODE_RWX (S_IXUSR | S_IXGRP | S_IXOTH | MODE_RW) +#define MODE_ALL (S_ISUID | S_ISGID | S_ISVTX | MODE_RWX) + +#if 1 +#include +typedef bool boolean; +#else /* Not char because of type promotion; NeXT gcc can't handle it. */ typedef int boolean; #define true 1 #define false 0 +#endif -/* Pointer to function returning boolean. */ -typedef boolean (*PFB)(); +struct predicate; + +/* Pointer to a predicate function. */ +typedef boolean (*PRED_FUNC)(char *pathname, struct stat *stat_buf, struct predicate *pred_ptr); /* The number of seconds in a day. */ #define DAYSECS 86400 @@ -70,6 +158,13 @@ enum comparison_type COMP_EQ }; +enum permissions_type +{ + PERM_AT_LEAST, + PERM_ANY, + PERM_EXACT +}; + enum predicate_type { NO_TYPE, @@ -93,27 +188,63 @@ enum predicate_precedence struct long_val { enum comparison_type kind; - unsigned long l_val; + boolean negative; /* Defined only when representing time_t. */ + uintmax_t l_val; +}; + +struct perm_val +{ + enum permissions_type kind; + mode_t val[2]; +}; + +/* dir_id is used to support loop detection in find.c and + * also to support the -samefile test. + */ +struct dir_id +{ + ino_t ino; + dev_t dev; }; struct size_val { enum comparison_type kind; int blocksize; - unsigned long size; + uintmax_t size; }; +#define NEW_EXEC 1 +/* +#undef NEW_EXEC +*/ + +#if !defined(NEW_EXEC) struct path_arg { short offset; /* Offset in `vec' of this arg. */ short count; /* Number of path replacements in this arg. */ char *origarg; /* Arg with "{}" intact. */ }; +#endif + +#include "buildcmd.h" struct exec_val { +#if defined(NEW_EXEC) + /* new-style */ + boolean multiple; /* -exec {} \+ denotes multiple argument. */ + struct buildcmd_control ctl; + struct buildcmd_state state; + char **replace_vec; /* Command arguments (for ";" style) */ + int num_args; + boolean use_current_dir; /* If nonzero, don't chdir to start dir */ + boolean close_stdin; /* If true, close stdin in the child. */ +#else struct path_arg *paths; /* Array of args with path replacements. */ char **vec; /* Array of args to pass to program. */ +#endif }; /* The format string for a -printf or -fprintf is chopped into one or @@ -137,12 +268,14 @@ struct format_val { struct segment *segment; /* Linked list of segments. */ FILE *stream; /* Output stream to print on. */ + boolean dest_is_tty; /* True if the destination is a terminal. */ + struct quoting_options *quote_opts; }; struct predicate { /* Pointer to the function that implements this predicate. */ - PFB pred_func; + PRED_FUNC pred_func; /* Only used for debugging, but defined unconditionally so individual modules can be compiled with -DDEBUG. */ @@ -156,12 +289,20 @@ struct predicate /* The precedence of this node. Only has meaning for operators. */ enum predicate_precedence p_prec; - /* True if this predicate node produces side effects. */ + /* True if this predicate node produces side effects. + If side_effects are produced + then optimization will not be performed */ boolean side_effects; + /* True if this predicate node requires default print be turned off. */ + boolean no_default_print; + /* True if this predicate node requires a stat system call to execute. */ boolean need_stat; + /* True if this predicate node requires knowledge of the file type. */ + boolean need_type; + /* Information needed by the predicate processor. Next to each member are listed the predicates that use it. */ union @@ -169,19 +310,21 @@ struct predicate char *str; /* fstype [i]lname [i]name [i]path */ struct re_pattern_buffer *regex; /* regex */ struct exec_val exec_vec; /* exec ok */ - struct long_val info; /* atime ctime mtime inum links */ + struct long_val info; /* atime ctime gid inum links mtime + size uid */ struct size_val size; /* size */ uid_t uid; /* user */ gid_t gid; /* group */ time_t time; /* newer */ - unsigned long perm; /* perm */ - unsigned long type; /* type */ - FILE *stream; /* fprint fprint0 */ - struct format_val printf_vec; /* printf fprintf */ + struct perm_val perm; /* perm */ + struct dir_id fileid; /* samefile */ + mode_t type; /* type */ + FILE *stream; /* ls fls fprint0 */ + struct format_val printf_vec; /* printf fprintf fprint */ } args; /* The next predicate in the user input sequence, - which repesents the order in which the user supplied the + which represents the order in which the user supplied the predicates on the command line. */ struct predicate *pred_next; @@ -190,30 +333,34 @@ struct predicate processed. */ struct predicate *pred_left; struct predicate *pred_right; + + const struct parser_table* parser_entry; }; +/* find.c. */ +int get_info PARAMS((const char *pathname, const char *name, struct stat *p, struct predicate *pred_ptr)); +int following_links(void); + + /* find library function declarations. */ /* dirname.c */ -char *dirname P_((char *path)); +char *dirname PARAMS((char *path)); /* error.c */ -void error P_((int status, int errnum, char *message, ...)); +void error PARAMS((int status, int errnum, char *message, ...)); /* listfile.c */ -void list_file P_((char *name, char *relname, struct stat *statp, FILE *stream)); -char *get_link_name P_((char *name, char *relname)); - -/* savedir.c */ -char *savedir P_((char *dir, unsigned name_size)); +void list_file PARAMS((char *name, char *relname, struct stat *statp, time_t current_time, int output_block_size, FILE *stream)); +char *get_link_name PARAMS((char *name, char *relname)); /* stpcpy.c */ #if !HAVE_STPCPY -char *stpcpy P_((char *dest, const char *src)); +char *stpcpy PARAMS((char *dest, const char *src)); #endif /* xgetcwd.c */ -char *xgetcwd P_((void)); +char *xgetcwd PARAMS((void)); /* xmalloc.c */ #if __STDC__ @@ -222,111 +369,243 @@ char *xgetcwd P_((void)); #define VOID char #endif -VOID *xmalloc P_((size_t n)); -VOID *xrealloc P_((VOID *p, size_t n)); - -/* xstrdup.c */ -char *xstrdup P_((char *string)); - /* find global function declarations. */ +/* find.c */ +/* SymlinkOption represents the choice of + * -P, -L or -P (default) on the command line. + */ +enum SymlinkOption + { + SYMLINK_NEVER_DEREF, /* Option -P */ + SYMLINK_ALWAYS_DEREF, /* Option -L */ + SYMLINK_DEREF_ARGSONLY /* Option -H */ + }; +extern enum SymlinkOption symlink_handling; /* defined in find.c. */ + +void set_follow_state PARAMS((enum SymlinkOption opt)); +void cleanup(void); + /* fstype.c */ -char *filesystem_type P_((char *path, char *relpath, struct stat *statp)); +char *filesystem_type PARAMS((const struct stat *statp, const char *path)); +char * get_mounted_filesystems (void); +dev_t * get_mounted_devices PARAMS((size_t *)); + + + +enum arg_type + { + ARG_OPTION, /* regular options like -maxdepth */ + ARG_POSITIONAL_OPTION, /* options whose position is important (-follow) */ + ARG_TEST, /* a like -name */ + ARG_PUNCTUATION, /* like -o or ( */ + ARG_ACTION /* like -print */ + }; + + +struct parser_table; +/* Pointer to a parser function. */ +typedef boolean (*PARSE_FUNC)(const struct parser_table *p, + char *argv[], int *arg_ptr); +struct parser_table +{ + enum arg_type type; + char *parser_name; + PARSE_FUNC parser_func; + PRED_FUNC pred_func; +}; /* parser.c */ -PFB find_parser P_((char *search_name)); -boolean parse_close P_((char *argv[], int *arg_ptr)); -boolean parse_open P_((char *argv[], int *arg_ptr)); -boolean parse_print P_((char *argv[], int *arg_ptr)); +const struct parser_table* find_parser PARAMS((char *search_name)); +boolean parse_open PARAMS((const struct parser_table* entry, char *argv[], int *arg_ptr)); +boolean parse_close PARAMS((const struct parser_table* entry, char *argv[], int *arg_ptr)); +boolean parse_print PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +void pred_sanity_check PARAMS((const struct predicate *predicates)); +void parse_begin_user_args PARAMS((char **args, int argno, const struct predicate *last, const struct predicate *predicates)); +void parse_end_user_args PARAMS((char **args, int argno, const struct predicate *last, const struct predicate *predicates)); +boolean parse_openparen PARAMS((const struct parser_table* entry, char *argv[], int *arg_ptr)); +boolean parse_closeparen PARAMS((const struct parser_table* entry, char *argv[], int *arg_ptr)); /* pred.c */ -boolean pred_amin P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_and P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_anewer P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_atime P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_close P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_cmin P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_cnewer P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_comma P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_ctime P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_empty P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_exec P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_false P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_fls P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_fprint P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_fprint0 P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_fprintf P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_fstype P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_gid P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_group P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_ilname P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_iname P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_inum P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_ipath P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_links P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_lname P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_ls P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_mmin P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_mtime P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_name P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_negate P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_newer P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_nogroup P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_nouser P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_ok P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_open P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_or P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_path P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_perm P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_print P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_print0 P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_prune P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_regex P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_size P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_true P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_type P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_uid P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_used P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_user P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -boolean pred_xtype P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); -char *find_pred_name P_((PFB pred_func)); +boolean pred_amin PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_and PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_anewer PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_atime PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_closeparen PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_cmin PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_cnewer PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_comma PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_ctime PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_delete PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_empty PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_exec PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_execdir PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_false PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_fls PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_fprint PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_fprint0 PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_fprintf PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_fstype PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_gid PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_group PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_ilname PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_iname PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_inum PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_ipath PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_links PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_lname PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_ls PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_mmin PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_mtime PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_name PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_negate PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_newer PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_nogroup PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_nouser PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_ok PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_okdir PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_openparen PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_or PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_path PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_perm PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_print PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_print0 PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_prune PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_quit PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_regex PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_samefile PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_size PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_true PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_type PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_uid PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_used PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_user PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); +boolean pred_xtype PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)); + + + +int launch PARAMS((const struct buildcmd_control *ctl, + struct buildcmd_state *buildstate)); + + +char *find_pred_name PARAMS((PRED_FUNC pred_func)); + + + #ifdef DEBUG -void print_tree P_((struct predicate *node, int indent)); -void print_list P_((struct predicate *node)); +void print_tree PARAMS((FILE*, struct predicate *node, int indent)); +void print_list PARAMS((FILE*, struct predicate *node)); +void print_optlist PARAMS((FILE *fp, struct predicate *node)); #endif /* DEBUG */ /* tree.c */ -struct predicate *get_expr P_((struct predicate **input, int prev_prec)); -boolean opt_expr P_((struct predicate **eval_treep)); -boolean mark_stat P_((struct predicate *tree)); +struct predicate * +get_expr PARAMS((struct predicate **input, short int prev_prec)); +boolean opt_expr PARAMS((struct predicate **eval_treep)); +boolean mark_stat PARAMS((struct predicate *tree)); +boolean mark_type PARAMS((struct predicate *tree)); /* util.c */ -char *basename P_((char *fname)); -struct predicate *get_new_pred P_((void)); -struct predicate *get_new_pred_chk_op P_((void)); -struct predicate *insert_primary P_((boolean (*pred_func )())); -void usage P_((char *msg)); +struct predicate *get_new_pred PARAMS((const struct parser_table *entry)); +struct predicate *get_new_pred_chk_op PARAMS((const struct parser_table *entry)); +struct predicate *insert_primary PARAMS((const struct parser_table *entry)); +struct predicate *insert_primary_withpred PARAMS((const struct parser_table *entry, PRED_FUNC fptr)); +void usage PARAMS((char *msg)); extern char *program_name; extern struct predicate *predicates; extern struct predicate *last_pred; -extern boolean do_dir_first; -extern int maxdepth; -extern int mindepth; -extern int curdepth; -extern time_t cur_day_start; -extern boolean full_days; -extern boolean no_leaf_check; -extern boolean stay_on_filesystem; -extern boolean stop_at_current_level; -extern boolean have_stat; -extern char *rel_pathname; -#ifndef HAVE_FCHDIR -extern char *starting_dir; -#else + +struct options +{ + /* If true, process directory before contents. True unless -depth given. */ + boolean do_dir_first; + + /* If >=0, don't descend more than this many levels of subdirectories. */ + int maxdepth; + + /* If >=0, don't process files above this level. */ + int mindepth; + + /* If true, do not assume that files in directories with nlink == 2 + are non-directories. */ + boolean no_leaf_check; + + /* If true, don't cross filesystem boundaries. */ + boolean stay_on_filesystem; + + /* If true, we ignore the problem where we find that a directory entry + * no longer exists by the time we get around to processing it. + */ + boolean ignore_readdir_race; + +/* If true, we issue warning messages + */ + boolean warnings; + time_t start_time; /* Time at start of execution. */ + + /* Seconds between 00:00 1/1/70 and either one day before now + (the default), or the start of today (if -daystart is given). */ + time_t cur_day_start; + + /* If true, cur_day_start has been adjusted to the start of the day. */ + boolean full_days; + + int output_block_size; /* Output block size. */ + + enum SymlinkOption symlink_handling; + + + /* Pointer to the function used to stat files. */ + int (*xstat) (const char *name, struct stat *statbuf); + + + /* Indicate if we can implement safely_chdir() using the O_NOFOLLOW + * flag to open(2). + */ + boolean open_nofollow_available; + + /* The variety of regular expression that we support. + * The default is POSIX Basic Regular Expressions, but this + * can be changed with the positional option, -regextype. + */ + int regex_options; +}; +extern struct options options; + + +struct state +{ + /* Current depth; 0 means current path is a command line arg. */ + int curdepth; + + /* If true, we have called stat on the current path. */ + boolean have_stat; + + /* If true, we know the type of the current path. */ + boolean have_type; + mode_t type; /* this is the actual type */ + + /* The file being operated on, relative to the current directory. + Used for stat, readlink, remove, and opendir. */ + char *rel_pathname; + + /* Length of current path. */ + int path_length; + + /* If true, don't descend past current directory. + Can be set by -prune, -maxdepth, and -xdev/-mount. */ + boolean stop_at_current_level; + + /* Status value to return to system. */ + int exit_status; +}; +extern struct state state; + +extern char const *starting_dir; extern int starting_desc; +#if ! defined HAVE_FCHDIR && ! defined fchdir +# define fchdir(fd) (-1) +#endif + #endif -extern int exit_status; -extern int path_length; -extern int (*xstat) (); -extern boolean dereference; diff --git a/src/bin/findutils/find/find.1 b/src/bin/findutils/find/find.1 index d6280d4046..9be362f5e0 100644 --- a/src/bin/findutils/find/find.1 +++ b/src/bin/findutils/find/find.1 @@ -1,13 +1,14 @@ -.TH FIND 1L \" -*- nroff -*- +.TH FIND 1 \" -*- nroff -*- .SH NAME find \- search for files in a directory hierarchy .SH SYNOPSIS -.B find -[path...] [expression] +.B find +[\-H] [\-L] [\-P] [path...] [expression] .SH DESCRIPTION This manual page documents the GNU version of .BR find . +GNU .B find searches the directory tree rooted at each given file name by evaluating the given expression from left to right, according to the @@ -17,41 +18,162 @@ known (the left hand side is false for \fIand\fR operations, true for .B find moves on to the next file name. .PP -The first argument that begins with `\-', `(', `)', `,', or `!' is taken -to be the beginning of the expression; any arguments before it are -paths to search, and any arguments after it are the rest of the -expression. If no paths are given, the current directory is used. If -no expression is given, the expression `\-print' is used. +If you are using +.B find +in an environment where security is important (for example if you are +using it to seach directories that are writable by other users), you +should read the "Security Considerations" chapter of the findutils +documentation, which is called \fBFinding Files\fP and comes with +findutils. That document also includes a lot more detail +and discussion than this manual page, so you may find it a more useful +source of information. +.SH OPTIONS +The `\-H', `\-L' and `\-P' options control the treatment of symbolic +links. Command-line arguments following these are taken to be names +of files or directories to be examined, up to the first argument that +begins with `\-', `(', `)', `,', or `!'. That argument and any +following arguments are taken to be the expression describing what is +to be searched for. If no paths are given, the current directory is +used. If no expression is given, the expression `\-print' is used +(but you should probably consider using `\-print0' instead, anyway). .PP +This manual page talks about `options' within the expression list. +These options control the behaviour of .B find -exits with status 0 if all files are processed successfully, greater -than 0 if errors occur. -.SH EXPRESSIONS +but are specified immediately after the last path name. The three +`real' options `\-H', `\-L' and `\-P' must appear before the first +path name, if at all. +.IP \-P +Never follow symbolic links. This is the default behaviour. When +.B find +examines or prints information a file, and the file is a symbolic +link, the information used shall be taken from the properties of the +symbolic link itself. + +.IP \-L +Follow symbolic links. When +.B find +examines or prints information about files, the information used shall +be taken from the properties of the file to which the link points, not +from the link itself (unless it is a broken symbolic link or +.B find +is unable to examine the file to which the link points). Use of this +option implies \-noleaf. If you later use the \-P option, \-noleaf +will still be in effect. If \-L is in effect and +.B find +discovers a symbolic link to a subdirectory during its search, +the subdirectory pointed to by the symbolic link will be searched. +.IP +When the \-L option is in effect, the \-type predicate will always +match against the type of the file that a symbolic link points to +rather than the link itself (unless the symbolic link is broken). +Using \-L causes the \-lname and \-ilname predicates always to return +false. + +.IP \-H +Do not follow symbolic links, except while processing the command +line arguments. When +.B find +examines or prints information about files, the information used +shall be taken from the properties of the symbolic link itself. The +only exception to this behaviour is when a file specified on the +command line is a symbolic link, and the link can be resolved. For +that situation, the information used is taken from whatever the link +points to (that is, the link is followed). The information about the +link itself is used as a fallback if the file pointed to by the +symbolic link cannot be examined. If \-H is in effect and one of the +paths specified on the command line is a symbolic link to a directory, +the contents of that directory will be examined (though of course +\-maxdepth 0 would prevent this). .P +If more than one of \-H, \-L and \-P is specified, each overrides the +others; the last one appearing on the command line takes effect. +Since it is the default, the \-P option should be considered to be in +effect unless either \-H or \-L is specified. + +GNU +.B find +frequently stats files during the processing of the command line +itself, before any searching has begun. These options also affect how +those arguments are processed. Specifically, there are a number of +tests that compare files listed on the command line against a file we +are currently considering. In each case, the file specified on the +command line will have been examined and some of its properties will +have been saved. If the named file is in fact a symbolic link, and +the \-P option is in effect (or if neither \-H nor \-L were +specified), the information used for the comparison will be taken from +the properties of the symbolic link. Otherwise, it will be taken from +the properties of the file the link points to. If +.B find +cannot follow the link (for example because it has insufficient +privileges or the link points to a nonexistent file) the properties of +the link itself will be used. +.P +When the \-H or \-L options are in effect, any symbolic links listed +as the argument of \-newer will be dereferenced, and the timestamp +will be taken from the file to which the symbolic link points. The +same consideration applies to \-anewer and \-cnewer. + +The \-follow option has a similar effect to \-L, though it takes +effect at the point where it appears (that is, if \-L is not used but +\-follow is, any symbolic links appearing after \-follow on the +command line will be dereferenced, and those before it will not). + +.P +.SH EXPRESSIONS The expression is made up of options (which affect overall operation -rather than the processing of a specific file, and always return true), -tests (which return a true or false value), and actions (which have side -effects and return a true or false value), all separated by operators. -\-and is assumed where the operator is omitted. If the expression contains -no actions other than \-prune, \-print is performed on all files -for which the expression is true. +rather than the processing of a specific file, and always return +true), tests (which return a true or false value), and actions (which +have side effects and return a true or false value), all separated by +operators. \-and is assumed where the operator is omitted. + +If the expression contains no actions other than \-prune, \-print is +performed on all files for which the expression is true. + .SS OPTIONS .P -All options always return true. They always take effect, rather than -being processed only when their place in the expression is reached. -Therefore, for clarity, it is best to place them at the beginning of -the expression. +All options always return true. Except for \-follow and \-daystart, +the options affect all tests, including tests specified before the +option. This is because the options are processed when the command +line is parsed, while the tests don't do anything until files are +examined. The \-follow and \-daystart options are different in this +respect, and have an effect only on tests which appear later in the +command line. Therefore, for clarity, it is best to place them at the +beginning of the expression. A warning is issued if you don't do +this. .IP \-daystart Measure times (for \-amin, \-atime, \-cmin, \-ctime, \-mmin, and \-mtime) -from the beginning of today rather than from 24 hours ago. +from the beginning of today rather than from 24 hours ago. This +option only affects tests which appear later on the command line. .IP \-depth Process each directory's contents before the directory itself. +.IP \-d +A synonym for \-depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. .IP \-follow -Dereference symbolic links. Implies \-noleaf. +Deprecated; use the \-L option instead. Dereference symbolic links. +Implies \-noleaf. The \-follow option affects only those tests which +appear after it on the command line. Unless the \-H or \-L option has +been specified, the position of the \-follow option changes the +behaviour of the \-newer predicate; any files listed as the argument +of \-newer will be dereferenced if they are symbolic links. The same +consideration applies to \-anewer and \-cnewer. Similarly, the \-type +predicate will always match against the type of the file that a +symbolic link points to rather than the link itself. Using \-follow +causes the \-lname and \-ilname predicates always to return false. .IP "\-help, \-\-help" Print a summary of the command-line usage of .B find and exit. +.IP \-ignore_readdir_race +Normally, \fBfind\fR will emit an error message when it fails to stat a file. +If you give this option and a file is deleted between the time \fBfind\fR +reads the name of the file from the directory and the time it tries to stat +the file, no error message will be issued. This also applies to files +or directories whose names are given on the command line. This option takes +effect at the time the command line is read, which means that you cannot search +one part of the filesystem with this option on and part of it with this option +off (if you need to do that, you will need to issue two \fBfind\fR commands +instead, one with the option and one without it). .IP "\-maxdepth \fIlevels\fR" Descend at most \fIlevels\fR (a non-negative integer) levels of directories below the command line arguments. `\-maxdepth 0' means @@ -64,6 +186,8 @@ the command line arguments. Don't descend directories on other filesystems. An alternate name for \-xdev, for compatibility with some other versions of .BR find . +.IP \-noignore_readdir_race +Turns off the effect of \-ignore_readdir_race. .IP "\-noleaf" Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when @@ -79,10 +203,27 @@ than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. +.IP "\-regextype \fItype\fR" +Changes the regular expression syntax understood by +.B \-regex +and +.B \-iregex +tests which occur later on the command line. Currently-implemented +types are emacs (this is the default), posix-awk, posix-basic, +posix-egrep and posix-extended. + .IP "\-version, \-\-version" Print the \fBfind\fR version number and exit. +.IP "\-warn, \-nowarn" +Turn warning messages on or off. These warnings apply only to the +command line usage, not to any conditions that +.B find +might encounter when it searches directories. The default behaviour +corresponds to \-warn if standard input is a tty, and to \-nowarn +otherwise. .IP \-xdev Don't descend directories on other filesystems. + .SS TESTS .P Numeric arguments can be specified as @@ -98,19 +239,33 @@ for exactly .IP "\-amin \fIn\fR" File was last accessed \fIn\fR minutes ago. .IP "\-anewer \fIfile\fR" -File was last accessed more recently than \fIfile\fR was modified. -\-anewer is affected by \-follow only if \-follow comes before -\-anewer on the command line. +File was last accessed more recently than \fIfile\fR was modified. If +\fIfile\fR is a symbolic link and the \-H option or the \-L option is +in effect, the access time of the file it points to is always +used. .IP "\-atime \fIn\fR" -File was last accessed \fIn\fR*24 hours ago. +File was last accessed \fIn\fR*24 hours ago. +When find figures out how many 24-hour periods ago the file +was last accessed, any fractional part is ignored, so to match +.B \-atime +.BR +1 , +a file has to have been accessed at least +.I two +days ago. .IP "\-cmin \fIn\fR" File's status was last changed \fIn\fR minutes ago. .IP "\-cnewer \fIfile\fR" -File's status was last changed more recently than \fIfile\fR was modified. -\-cnewer is affected by \-follow only if \-follow comes before -\-cnewer on the command line. +File's status was last changed more recently than \fIfile\fR was +modified. If \fIfile\fR is a symbolic link and the \-H option or the +\-L option is in effect, the status-change time of the file it points +to is always used. + .IP "\-ctime \fIn\fR" File's status was last changed \fIn\fR*24 hours ago. +See the comments for +.B \-atime +to understand how rounding affects the interpretation of file status +change times. .IP \-empty File is empty and is either a regular file or a directory. .IP \-false @@ -127,75 +282,157 @@ File's numeric group ID is \fIn\fR. File belongs to group \fIgname\fR (numeric group ID allowed). .IP "\-ilname \fIpattern\fR" Like \-lname, but the match is case insensitive. +If the \-L option or the \-follow option is in effect, this test +returns false unless the symbolic link is broken. .IP "\-iname \fIpattern\fR" Like \-name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', -`fOo', etc. +`fOo', etc. In these patterns, unlike filename expansion by the +shell, an initial '.' can be matched by '*'. That is, +.B find \-name *bar +will match the file `.foobar'. Please note that you should quote +patterns as a matter of course, otherwise the shell will expand any +wildcard characters in them. + .IP "\-inum \fIn\fR" -File has inode number \fIn\fR. +File has inode number \fIn\fR. It is normally easier to use the +.B \-samefile +test instead. .IP "\-ipath \fIpattern\fR" -Like \-path, but the match is case insensitive. +Behaves in the same way as \-iwholename. This option is deprecated, +so please do not use it. .IP "\-iregex \fIpattern\fR" Like \-regex, but the match is case insensitive. +.IP "\-iwholename \fIpattern\fR" +Like \-wholename, but the match is case insensitive. .IP "\-links \fIn\fR" File has \fIn\fR links. .IP "\-lname \fIpattern\fR" File is a symbolic link whose contents match shell pattern \fIpattern\fR. The metacharacters do not treat `/' or `.' specially. +If the \-L option or the \-follow option is in effect, this test +returns false unless the symbolic link is broken. .IP "\-mmin \fIn\fR" File's data was last modified \fIn\fR minutes ago. .IP "\-mtime \fIn\fR" File's data was last modified \fIn\fR*24 hours ago. +See the comments for +.B \-atime +to understand how rounding affects the interpretation of file +modification times. .IP "\-name \fIpattern\fR" Base of file name (the path with the leading directories removed) matches shell pattern \fIpattern\fR. The metacharacters (`*', `?', -and `[]') do not match a `.' at the start of the base name. To ignore -a directory and the files under it, use \-prune; see an example in the -description of \-path. +and `[]') match a `.' at the start of the base name (this is a change +in findutils-4.2.2; see section STANDARDS CONFORMANCE below). To ignore a +directory and the files under it, use \-prune; see an example in the +description of \-wholename. Braces are not recognised as being +special, despite the fact that some shells including Bash imbue braces +with a special meaning in shell patterns. The filename matching is +performed with the use of the +.BR fnmatch (3) +library function. Don't forget to enclose the pattern in quotes +in order to protect it from expansion by the shell. + .IP "\-newer \fIfile\fR" -File was modified more recently than \fIfile\fR. -\-newer is affected by \-follow only if \-follow comes before -\-newer on the command line. +File was modified more recently than \fIfile\fR. If \fIfile\fR is a +symbolic link and the \-H option or the \-L option is in effect, the +modification time of the file it points to is always used. .IP \-nouser No user corresponds to file's numeric user ID. .IP \-nogroup No group corresponds to file's numeric group ID. .IP "\-path \fIpattern\fR" -File name matches shell pattern \fIpattern\fR. The metacharacters do -not treat `/' or `.' specially; so, for example, -.br -.in +1i -find . \-path './sr*sc' -.br -.in -1i -will print an entry for a directory called './src/misc' (if one -exists). To ignore a whole directory tree, use \-prune rather than -checking every file in the tree. For example, to skip the -directory `src/emacs' and all files and directories under it, and -print the names of the other files found, do something like this: -.br -.in +1i -find . \-path './src/emacs' -prune -o -print -.br -.in -1i +See \-wholename. The predicate \-path is also supported by HP-UX +.BR find . .IP "\-perm \fImode\fR" File's permission bits are exactly \fImode\fR (octal or symbolic). -Symbolic modes use mode 0 as a point of departure. +Since an exact match is required, if you want to use this form for +symbolic modes, you may have to specify a rather complex mode string. +For example '\-perm g=w' will only match files which have mode 0020 +(that is, ones for which group write permission is the only permission +set). It is more likely that you will want to use the '/' or '-' +forms, for example '\-perm \-g=w', which matches any file with group +write permission. See the +.B EXAMPLES +section for some illustrative examples. .IP "\-perm \-\fImode\fR" All of the permission bits \fImode\fR are set for the file. +Symbolic modes are accepted in this form, and this is usually the way +in which would want to use them. You must specify 'u', 'g' or 'o' if +you use a symbolic mode. See the +.B EXAMPLES +section for some illustrative examples. +.IP "\-perm /\fImode\fR" +Any of the permission bits \fImode\fR are set for the file. Symbolic +modes are accepted in this form. You must specify 'u', 'g' or 'o' if +you use a symbolic mode. See the +.B EXAMPLES +section for some illustrative examples. If no permission bits in +.I mode +are set, this test currently matches no files. However, it will soon +be changed to match any file (the idea is to be more consistent with +the behaviour of +.B perm +.BR \-000 ). .IP "\-perm +\fImode\fR" -Any of the permission bits \fImode\fR are set for the file. +Deprecated, old way of searching for files with any of the permission +bits in \fImode\fR set. You should use +.B \-perm \fI/mode\fR +instead. Trying to use the '+' syntax with symbolic modes will yield +surprising results. For example, '+u+x' is a valid symbolic mode +(equivalent to +u,+x, i.e. 0111) and will therefore not be evaluated +as +.B \-perm +\fImode\fR +but instead as the exact mode specifier +.B \-perm \fImode\fR +and so it matches files with exact permissions 0111 instead of files with any +execute bit set. If you found this paragraph confusing, you're not +alone - just use +.B \-perm /\fImode\fR. +This form of the +.B \-perm +test is deprecated because the POSIX specification requires the +interpretation of a leading '+' as being part of a symbolic mode, and +so we switched to using '/' instead. + .IP "\-regex \fIpattern\fR" File name matches regular expression \fIpattern\fR. This is a match on the whole path, not a search. For example, to match a file named `./fubar3', you can use the regular expression `.*bar.' or `.*b.*3', -but not `b.*r3'. -.IP "\-size \fIn\fR[bckw]" -File uses \fIn\fP units of space. The units are 512-byte blocks by -default or if `b' follows \fIn\fP, bytes if `c' follows \fIn\fP, -kilobytes if `k' follows \fIn\fP, or 2-byte words if `w' follows \fIn\fP. +but not `f.*r3'. The regular expressions understood by +.B find +are by default Emacs Regular Expressions, but this can be +changed with the +.B \-regextype +option. +.IP "\-samefile \fIname\fR" +File refers to the same inode as \fIname\fR. When \-L is in effect, +this can include symbolic links. +.IP "\-size \fIn\fR[cwbkMG]" +File uses \fIn\fP units of space. The following suffixes +can be used: +.RS +.IP `b' +for 512-byte blocks (this is the default if no suffix is used) +.IP `c' +for bytes +.IP `w' +for two-byte words +.IP `k' +for Kilobytes (units of 1024 bytes) +.IP `M' +for Megabytes (units of 1048576 bytes) +.IP `G' +for Gigabytes (units of 1073741824 bytes) +.RE +.IP The size does not count indirect blocks, but it does count blocks in -sparse files that are not actually allocated. +sparse files that are not actually allocated. Bear in mind that the +`%k' and `%b' format specifiers of \-printf handle sparse files +differently. The `b' suffix always denotes 512-byte blocks and never +1 Kilobyte blocks, which is different to the behaviour of \-ls. + .IP \-true Always true. .IP "\-type \fIc\fR" @@ -212,9 +449,13 @@ named pipe (FIFO) .IP f regular file .IP l -symbolic link +symbolic link; this is never true if the \-L option or the \-follow +option is in effect, unless the symbolic link is broken. If you want +to search for symbolic links when \-L is in effect, use \-xtype. .IP s socket +.IP D +door (Solaris) .RE .IP "\-uid \fIn\fR" File's numeric user ID is \fIn\fR. @@ -222,13 +463,37 @@ File's numeric user ID is \fIn\fR. File was last accessed \fIn\fR days after its status was last changed. .IP "\-user \fIuname\fR" File is owned by user \fIuname\fR (numeric user ID allowed). +.IP "\-wholename \fIpattern\fR" +File name matches shell pattern \fIpattern\fR. The metacharacters do +not treat `/' or `.' specially; so, for example, +.br +.in +1i +find . \-wholename './sr*sc' +.br +.in -1i +will print an entry for a directory called './src/misc' (if one +exists). To ignore a whole directory tree, use \-prune rather than +checking every file in the tree. For example, to skip the +directory `src/emacs' and all files and directories under it, and +print the names of the other files found, do something like this: +.br +.in +1i +find . \-wholename './src/emacs' \-prune \-o \-print +.br +.in -1i .IP "\-xtype \fIc\fR" The same as \-type unless the file is a symbolic link. For symbolic -links: if \-follow has not been given, true if the file is a link to a -file of type \fIc\fR; if \-follow has been given, true if \fIc\fR is -`l'. In other words, for symbolic links, \-xtype checks the type of -the file that \-type does not check. +links: if the \-H or \-P option was specified, true if the file is a +link to a file of type \fIc\fR; if the \-L option has been given, true +if \fIc\fR is `l'. In other words, for symbolic links, \-xtype checks +the type of the file that \-type does not check. + .SS ACTIONS +.IP "\-delete\fR" +Delete files; true if removal succeeded. If the removal failed, an +error message is issued. Use of this action automatically turns on +the '\-depth' option. + .IP "\-exec \fIcommand\fR ;" Execute \fIcommand\fR; true if 0 status is returned. All following arguments to @@ -240,36 +505,113 @@ command, not just in arguments where it is alone, as in some versions of .BR find . Both of these constructions might need to be escaped (with a `\e') or -quoted to protect them from expansion by the shell. The command is -executed in the starting directory. +quoted to protect them from expansion by the shell. See the +.B EXAMPLES +section for examples of the use of the `\-exec' option. The specified +command is run once for each matched file. +The command is executed in the starting directory. There are +unavoidable security problems surrounding use of the \-exec option; +you should use the \-execdir option instead. + +.IP "\-exec \fIcommand\fR {} +" +This variant of the \-exec option runs the specified command on the +selected files, but the command line is built by appending each +selected file name at the end; the total number of invocations of the +command will be much less than the number of matched files. The +command line is built in much the same way that +.B xargs +builds its command lines. Only one instance of '{}' is allowed within +the command. The command is executed in the starting directory. + +.IP "\-execdir \fIcommand\fR ;" +.IP "\-execdir \fIcommand\fR {} +" +Like \-exec, but the specified command is run from the subdirectory +containing the matched file, which is not normally the directory in +which you started +.BR find . +This a much more secure method for invoking commands, as it avoids +race conditions during resolution of the paths to the matched files. +As with the \-exec option, the '+' form of \-execdir will build a +command line to process more than one matched file, but any given +invocation of +.I command +will only list files that exist in the same subdirectory. If you use +this option, you must ensure that your +.B $PATH +environment variable does not reference the current directory; +otherwise, an attacker can run any commands they like by leaving an +appropriately-named file in a directory in which you will run +\-execdir. + .IP "\-fls \fIfile\fR" True; like \-ls but write to \fIfile\fR like \-fprint. +The output file is always created, even if the predicate is never +matched. +See the +.B UNUSUAL FILENAMES +section for information about how unusual characters in filenames are handled. + .IP "\-fprint \fIfile\fR" True; print the full file name into file \fIfile\fR. If \fIfile\fR does not exist when \fBfind\fR is run, it is created; if it does exist, it is truncated. The file names ``/dev/stdout'' and ``/dev/stderr'' are handled specially; they refer to the standard output and standard error output, respectively. +The output file is always created, even if the predicate is never matched. +See the +.B UNUSUAL FILENAMES +section for information about how unusual characters in filenames are handled. .IP "\-fprint0 \fIfile\fR" True; like \-print0 but write to \fIfile\fR like \-fprint. +The output file is always created, even if the predicate is never matched. +See the +.B UNUSUAL FILENAMES +section for information about how unusual characters in filenames are handled. .IP "\-fprintf \fIfile\fR \fIformat\fR" True; like \-printf but write to \fIfile\fR like \-fprint. +The output file is always created, even if the predicate is never matched. +See the +.B UNUSUAL FILENAMES +section for information about how unusual characters in filenames are handled. .IP "\-ok \fIcommand\fR ;" Like \-exec but ask the user first (on the standard input); if the response does not start with `y' or `Y', do not run the command, and -return false. +return false. If the command is run, its standard input is redirected +from +.BR /dev/null . + .IP \-print -True; print the full file name on the standard output, followed by a newline. +True; print the full file name on the standard output, followed by a +newline. If you are piping the output of +.B find +into another program and there is the faintest possibility that the files +which you are searching for might contain a newline, then you should +seriously consider using the `\-print0' option instead of `\-print'. +See the +.B UNUSUAL FILENAMES +section for information about how unusual characters in filenames are handled. +.IP "\-okdir \fIcommand\fR ;" +Like \-execdir but ask the user first (on the standard input); if the +response does not start with `y' or `Y', do not run the command, and +return false. If the command is run, its standard input is redirected +from +.BR /dev/null . .IP \-print0 True; print the full file name on the standard output, followed by a -null character. This allows file names that contain newlines to be -correctly interpreted by programs that process the \fBfind\fR output. +null character (instead of the newline character that `\-print' uses). +This allows file names that contain newlines or other types of white +space to be correctly interpreted by programs that process the +\fBfind\fR output. This option corresponds to the `\-0' option of +.BR xargs . .IP "\-printf \fIformat\fR" True; print \fIformat\fR on the standard output, interpreting `\e' escapes and `%' directives. Field widths and precisions can be -specified as with the `printf' C function. Unlike \-print, \-printf -does not add a newline at the end of the string. The escapes and -directives are: +specified as with the `printf' C function. Please note that many of +the fields are printed as %s rather than %d, and this may mean that +flags don't work as you might expect. This also means that the `\-' +flag does work (it forces fields to be left-aligned). Unlike \-print, +\-printf does not add a newline at the end of the string. The escapes +and directives are: .RS .IP \ea Alarm bell. @@ -287,8 +629,12 @@ Carriage return. Horizontal tab. .IP \ev Vertical tab. +.IP \e\0 +ASCII NUL. .IP \e\e A literal backslash (`\e'). +.IP \eNNN +The character whose ASCII code is NNN (octal). .PP A `\e' character followed by any other character is treated as an ordinary character, so they both are printed. @@ -301,7 +647,7 @@ File's last access time in the format specified by \fIk\fR, which is either `@' or a directive for the C `strftime' function. The possible values for \fIk\fR are listed below; some of them might not be available on all systems, due to differences in `strftime' between -systems. +systems. .RS .IP @ seconds since Jan. 1, 1970, 00:00 GMT. @@ -325,6 +671,10 @@ time, 12-hour (hh:mm:ss [AP]M) second (00..61) .IP T time, 24-hour (hh:mm:ss) +.IP + +Date and time, separated by '+', for example `2004\-04\-28+22:22:05'. +The time is given in the current timezone (which may be affected by +setting the TZ environment variable). This is a GNU extension. .IP X locale's time representation (H:M:S) .IP Z @@ -365,7 +715,9 @@ last two digits of year (00..99) year (1970...) .RE .IP %b -File's size in 512-byte blocks (rounded up). +The amount of disk space used for this file in 512-byte blocks. Since disk +space is allocated in multiples of the filesystem block size this is usually +greater than %s/512, but it can also be smaller if the file is a sparse file. .IP %c File's last status change time in the format returned by the C `ctime' function. @@ -375,6 +727,9 @@ which is the same as for %A. .IP %d File's depth in the directory tree; 0 means the file is a command line argument. +.IP %D +The device number on which the file exists (the st_dev field of struct +stat), in decimal. .IP %f File's name with any leading directories removed (only the last element). .IP %F @@ -386,16 +741,31 @@ File's group name, or numeric group ID if the group has no name. File's numeric group ID. .IP %h Leading directories of file's name (all but the last element). +If the file name contains no slashes (since it is in the current +directory) the %h specifier expands to ".". .IP %H Command line argument under which file was found. .IP %i File's inode number (in decimal). .IP %k -File's size in 1K blocks (rounded up). +The amount of disk space used for this file in 1K blocks. Since disk space is +allocated in multiples of the filesystem block size this is usually greater +than %s/1024, but it can also be smaller if the file is a sparse file. .IP %l Object of symbolic link (empty string if file is not a symbolic link). .IP %m -File's permission bits (in octal). +File's permission bits (in octal). This option uses the 'traditional' +numbers which most Unix implementations use, but if your particular +implementation uses an unusual ordering of octal permissions bits, you +will see a difference between the actual value of the file's mode and +the output of %m. Normally you will want to have a leading +zero on this number, and to do this, you should use the +.B # +flag (as in, for example, '%#m'). +.IP %M +File's permissions (in symbolic form, as for +.BR ls ). +This directive is supported in findutils 4.2.5 and later. .IP %n Number of hard links to file. .IP %p @@ -415,18 +785,119 @@ which is the same as for %A. File's user name, or numeric user ID if the user has no name. .IP %U File's numeric user ID. +.IP %y +File's type (like in ls \-l), U=unknown type (shouldn't happen) +.IP %Y +File's type (like %y), plus follow symlinks: L=loop, N=nonexistent .PP -A `%' character followed by any other character is discarded (but the -other character is printed). +A `%' character followed by any other character is discarded, but the +other character is printed (don't rely on this, as further format +characters may be introduced). A `%' at the end of the format +argument causes undefined behaviour since there is no following +character. In some locales, it may hide your door keys, while in +others it may remove the final page from the novel you are reading. + +The %m and %d directives support the +.B # +, +.B 0 +and +.B + +flags, but the other directives do not, even if they +print numbers. Numeric directives that do not support these flags +include +.BR G , +.BR U , +.BR b , +.BR D , +.B k +and +.BR n . +The `\-' format flag is supported and changes the alignment of a field +from right-justified (which is the default) to left-justified. +.PP +See the +.B UNUSUAL FILENAMES +section for information about how unusual characters in filenames are handled. + + .RE .IP \-prune -If \-depth is not given, true; do not descend the current directory. +If \-depth is not given, true; if the file is a directory, do not descend +into it. .br If \-depth is given, false; no effect. + +.IP "\-quit" +Exit immediately. No child processes will be left running, but no more +paths specified on the command line will be processed. For example, +.B find /tmp/foo /tmp/bar \-print \-quit +will print only +.BR /tmp/foo . +Any command lines which have been built up with +.B \-execdir ... {} + +will be invoked before +.B find +exits. The exit status may or may not be zero, depending on whether +an error has already occurred. + .IP \-ls True; list current file in `ls \-dils' format on standard output. The block counts are of 1K blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. +See the +.B UNUSUAL FILENAMES +section for information about how unusual characters in filenames are handled. + + +.SS UNUSUAL FILENAMES +Many of the actions of +.B find +result in the printing of data which is under the control of other +users. This includes file names, sizes, modification times and so +forth. File names are a potential problem since they can contain any +character except '\\0' and '/'. Unusual characters in file names can +do unexpected and often undesirable things to your terminal (for +example, changing the settings of your function keys on some +terminals). Unusual characters are handled differently by various +actions, as described below. +.IP "\-print0, \-fprint0\" +Always print the exact filename, unchanged, even if the output is +going to a terminal. +.IP "\-ls, \-fls" +Unusual characters are always escaped. White space, backslash, and +double quote characters are printed using C-style escaping (for +example '\\f', '\\"'). Other unusual characters are printed using an +octal escape. Other printable characters (for \-ls and \-fls these are +the characters between octal 041 and 0176) are printed as-is. +.IP "\-printf, \-fprintf" +If the output is not going to a terminal, it is printed as-is. +Otherwise, the result depends on which directive is in use. The +directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are +not under control of files' owners, and so are printed as-is. The +directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have +values which are under the control of files' owners but which cannot +be used to send arbitrary data to the terminal, and so these are +printed as-is. The directives %f, %h, %l, %p and %P are quoted. This +quoting is performed in the same way as for GNU +.BR ls . +This is not the same quoting mechanism as the one used for \-ls and +\-fls. If you are able to decide what format to use for the output +of +.B find +then it is normally better to use '\\0' as a terminator +than to use newline, as file names can contain white space and newline +characters. +.IP "\-print, \-fprint" +Quoting is handled in the same way as for \-printf and \-fprintf. +If you are using +.B find +in a script or in a situation where the matched files might have +arbitrary names, you should consider using \-print0 instead of +\-print. +.P +The \-ok and \-okdir actions print the current filename as-is. This +may change in a future release. .SS OPERATORS .P Listed in order of decreasing precedence: @@ -435,21 +906,356 @@ Force precedence. .IP "! \fIexpr\fR" True if \fIexpr\fR is false. .IP "\-not \fIexpr\fR" -Same as ! \fIexpr\fR. +Same as ! \fIexpr\fR, but not POSIX compliant. .IP "\fIexpr1 expr2\fR" -And (implied); \fIexpr2\fR is not evaluated if \fIexpr1\fR is false. +Two expressions in a row are taken to be joined with an +implied "and"; \fIexpr2\fR is not evaluated if \fIexpr1\fR is false. .IP "\fIexpr1\fR \-a \fIexpr2\fR" Same as \fIexpr1 expr2\fR. .IP "\fIexpr1\fR \-and \fIexpr2\fR" -Same as \fIexpr1 expr2\fR. +Same as \fIexpr1 expr2\fR, but not POSIX compliant. .IP "\fIexpr1\fR \-o \fIexpr2\fR" Or; \fIexpr2\fR is not evaluated if \fIexpr1\fR is true. .IP "\fIexpr1\fR \-or \fIexpr2\fR" -Same as \fIexpr1\fR \-o \fIexpr2\fR. +Same as \fIexpr1\fR \-o \fIexpr2\fR, but not POSIX compliant. .IP "\fIexpr1\fR , \fIexpr2\fR" List; both \fIexpr1\fR and \fIexpr2\fR are always evaluated. The value of \fIexpr1\fR is discarded; the value of the list is the -value of \fIexpr2\fR. +value of \fIexpr2\fR. +The comma operator can be useful for searching for several +different types of thing, but traversing the filesystem hierarchy only +once. The +.B \-fprintf +action can be used to list the various matched items into several +different output files. + + +.SH "STANDARDS CONFORMANCE" +The following options are specified in the POSIX standard +(IEEE Std 1003.1, 2003 Edition): +.IP "\-H" +This option is supported. +.IP "\-L" +This option is supported. +.IP "\-name" +This option is supported, but POSIX conformance depends on the +POSIX conformance of the system's +.BR fnmatch (3) +library function. As of findutils-4.2.2, shell metacharacters +('*'. '?' or '[]' for example) will match a leading '.', because +IEEE PASC interpretation 126 requires this. This is a change from +previous versions of findutils. +.IP "\-type" +Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. +GNU find also supports `D', representing a Door, where the OS provides these. + +.IP "\-ok" +Supported. Interpretation of the response is not locale-dependent +(see ENVIRONMENT VARIABLES). + +.IP "\-newer" +Supported. If the file specified is a symbolic link, it is always +dereferenced. This is a change from previous behaviour, which used to +take the relevant time from the symbolic link; see the HISTORY section +below. + +.IP "Other predicates" +The predicates +`\-atime', +`\-ctime', +`\-depth', +`\-group', +`\-links', +`\-mtime', +`\-nogroup', +`\-nouser', +`\-perm', +`\-print', +`\-prune', +`\-size', +`\-user' and +`\-xdev', +are all supported. + +.P +The POSIX standard specifies parentheses `(', `)', negation `!' and the +`and' and `or' operators (`\-a', `\-o'). +.P +All other options, predicates, expressions and so forth are extensions +beyond the POSIX standard. Many of these extensions are not unique to +GNU find, however. +.P +The POSIX standard requires that +.IP +The +.B find +utility shall detect infinite loops; that is, entering a +previously visited directory that is an ancestor of the last file +encountered. When it detects an infinite loop, find shall write a +diagnostic message to standard error and shall either recover its +position in the hierarchy or terminate. +.P +The link count of directories which contain entries which are hard +links to an ancestor will often be lower than they otherwise should +be. This can mean that GNU find will sometimes optimise away the +visiting of a subdirectory which is actually a link to an ancestor. +Since +.B find +does not actually enter such a subdirectory, it is allowed to avoid +emitting a diagnostic message. Although this behaviour may be +somewhat confusing, it is unlikely that anybody actually depends on +this behaviour. If the leaf optimisation has been turned off with +.BR \-noleaf , +the directory entry will always be examined and the diagnostic message +will be issued where it is appropriate. Symbolic links cannot be used +to create filesystem cycles as such, but if the \-L option or the +\-follow option is in use, a diagnostic message is issued when +.B find +encounters a loop of symbolic links. As with loops containing hard +links, the leaf optimisation will often mean that +.B find +knows that it doesn't need to call +.I stat() +or +.I chdir() +on the symbolic link, so this diagnostic is frequently not necessary. +.P +The \-d option is supported for compatibility with various BSD systems, +but you should use the POSIX-compliant option \-depth instead. +.P +The POSIXLY_CORRECT environment variable does not affect the behaviour +of the \-regex or \-iregex tests because those tests aren't specified in +the POSIX standard. +.SH "ENVIRONMENT VARIABLES" +.IP LANG +Provides a default value for the internationalization variables that +are unset or null. +.IP LC_ALL +If set to a non-empty string value, override the values of all the +other internationalization variables. +.IP LC_COLLATE +The POSIX standard specifies that this variable affects the pattern +matching to be used for the `\-name' option. GNU find uses the +.BR fnmatch (3) +library function, and so support for `LC_COLLATE' depends on the +system library. +.IP +POSIX also specifies that the `LC_COLLATE' environment +variable affects the interpretation of the user's response to the +query issued by `\-ok', but this is not the case for GNU find. +.IP LC_CTYPE +This variable affects the treatment of character classes used with +the `\-name' test, if the system's +.BR fnmatch (3) +library function supports this. It has no effect on the behaviour +of the `\-ok' expression. +.IP LC_MESSAGES +Determines the locale to be used for internationalised messages. +.IP NLSPATH +Determines the location of the internationalisation message catalogues. +.IP PATH +Affects the directories which are searched to find the executables +invoked by `\-exec', `\-execdir', `\-ok' and `\-okdir'. +.IP POSIXLY_CORRECT +Determines the block size used by `\-ls' and `\-fls'. +If `POSIXLY_CORRECT' is set, blocks are units of 512 bytes. Otherwise +they are units of 1024 bytes. +.IP TZ +Affects the time zone used for some of the time-related format +directives of \-printf and \-fprintf. +.SH "EXAMPLES" +.nf +.B find /tmp \-name core \-type f \-print | xargs /bin/rm \-f + +.fi +Find files named +.B core +in or below the directory +.B /tmp +and delete them. Note that this will work incorrectly if there are +any filenames containing newlines, single or double quotes, or spaces. +.P +.B find /tmp \-name core \-type f \-print0 | xargs \-0 /bin/rm \-f + +.fi +Find files named +.B core +in or below the directory +.B /tmp +and delete them, processing filenames in such a way that file or +directory names containing single or double quotes, spaces or newlines +are correctly handled. The +.B \-name +test comes before the +.B \-type +test in order to avoid having to call +.B stat(2) +on every file. + +.P +.nf +.B find . \-type f \-exec file '{}' \e\; + +.fi +Runs `file' on every file in or below the current directory. Notice +that the braces are enclosed in single quote marks to protect them +from interpretation as shell script punctuation. The semicolon is +similarly protected by the use of a backslash, though ';' could have +been used in that case also. + +.P +.nf +.B find / \t\e( \-perm \-4000 \-fprintf /root/suid.txt '%#m %u %p\en' \e) , \e +.B \t\t\e( \-size +100M \-fprintf /root/big.txt '%\-10s %p\en' \e) + +.fi +Traverse the filesystem just once, listing setuid files and +directories into +.B /root/suid.txt +and large files into +.BR /root/big.txt . + +.P +.nf +.B find $HOME \-mtime 0 + +.fi +Search for files in your home directory which have been modified in +the last twenty-four hours. This command works this way because the +time since each file was last modified is divided by 24 hours and any +remainder is discarded. That means that to match +.B \-mtime +.BR 0 , +a file will have to have a modification in the past which is less than +24 hours ago. + + +.P +.nf +.B find . \-perm 664 + +.fi +Search for files which have read and write permission for their owner, +and group, but which other users can read but not write to. Files +which meet these criteria but have other permissions bits set (for +example if someone can execute the file) will not be matched. + +.P +.nf +.B find . \-perm -664 + +.fi +Search for files which have read and write permission for their owner +and group, and which other users can read, without regard to the +presence of any extra permission bits (for example the executable +bit). This will match a file which has mode 0777, for example. + +.P +.nf +.B find . \-perm /222 + +.fi +Search for files which are writable by somebody (their owner, or +their group, or anybody else). + +.P +.nf +.B find . \-perm /220 +.B find . \-perm /u+w,g+w +.B find . \-perm /u=w,g=w + +.fi +All three of these commands do the same thing, but the first one uses +the octal representation of the file mode, and the other two use the +symbolic form. These commands all search for files which are +writable by either their owner or their group. The files don't have +to be writable by both the owner and group to be matched; either will +do. + +.P +.nf +.B find . \-perm -220 +.B find . \-perm \-g+w,u+w + +.fi +Both these commands do the same thing; search for files which are +writable by both their owner and their group. + +.P +.nf +.B find . \-perm \-444 \-perm /222 ! \-perm /111 +.B find . \-perm \-a+r \-perm /a+w ! \-perm /a+x + +.fi +These two commands both search for files that are readable for +everybody (\-perm \-444 or \-perm \-a+r), have at least on write bit +set (\-perm /222 or \-perm /a+w) but are not executable for anybody (! +\-perm /111 and ! \-perm /a+x respectively) + +.SH EXIT STATUS +.PP +.B find +exits with status 0 if all files are processed successfully, greater +than 0 if errors occur. This is deliberately a very broad +description, but if the return value is non-zero, you should not rely +on the correctness of the results of +.BR find . + .SH "SEE ALSO" -\fBlocate\fP(1L), \fBlocatedb\fP(5L), \fBupdatedb\fP(1L), \fBxargs\fP(1L) -\fBFinding Files\fP (on-line in Info, or printed) +\fBlocate\fP(1), \fBlocatedb\fP(5), \fBupdatedb\fP(1), \fBxargs\fP(1), +\fBchmod\fP(1), \fBfnmatch\fP(3), \fBregex\fP(7), \fBstat\fP(2), +\fBlstat\fP(2), \fBls\fP(1), \fBprintf\fP(3), \fBstrftime\fP(3), +\fBctime\fP(3), \fBFinding Files\fP (on-line in Info, or printed). +.SH "HISTORY" +As of findutils-4.2.2, shell metacharacters ('*'. '?' or '[]' for +example) used in filename patterns will match a leading '.', because +IEEE POSIX interpretation 126 requires this. +.SH "NON-BUGS" +.nf +.B $ find . \-name *.c \-print +find: paths must precede expression +Usage: find [-H] [-L] [-P] [path...] [expression] +.fi +.P +This happens because +.I *.c +has been expanded by the shell +resulting in +.B find +actually receiving a command line like this: +.nf + +.B find . \-name bigram.c code.c frcode.c locate.c \-print + +.fi +That command is of course not going to work. Instead of doing things +this way, you should enclose the pattern in quotes: +.nf +.B $ find . \-name \'*.c\' \-print +.fi + +.SH "BUGS" +.P +The test +.B \-perm /000 +currently matches no files, but for greater consistency with +.B \-perm +.BR \-000 , +this will be changed to match all files; this change will probably be +made in early 2006. Meanwhile, a warning message is given if you do this. +.P +There are security problems inherent in the behaviour that the POSIX +standard specifies for +.BR find , +which therefore cannot be fixed. For example, the \-exec action is +inherently insecure, and \-execdir should be used instead. +Please see \fBFinding Files\fP for more information. +.P +The best way to report a bug is to use the form at +http://savannah.gnu.org/bugs/?group=findutils. +The reason for this is that you will then be able to track progress in +fixing the problem. Other comments about \fBfind\fP(1) and about +the findutils package in general can be sent to the +.I bug\-findutils +mailing list. To join the list, send email to +.IR bug\-findutils\-request@gnu.org . diff --git a/src/bin/findutils/find/find.c b/src/bin/findutils/find/find.c index 361f2c416c..7fb06a91f5 100644 --- a/src/bin/findutils/find/find.c +++ b/src/bin/findutils/find/find.c @@ -1,53 +1,97 @@ /* find -- search for files in a directory hierarchy - Copyright (C) 1990, 91, 92, 93, 94 Free Software Foundation, Inc. + Copyright (C) 1990, 91, 92, 93, 94, 2000, + 2003, 2004, 2005, 2007 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - + along with this program. If not, see . +*/ /* GNU find was written by Eric Decker , - with enhancements by David MacKenzie , + with enhancements by David MacKenzie , Jay Plett , and Tim Wood . The idea for -print0 and xargs -0 came from - Dan Bernstein . */ + Dan Bernstein . + Improvements have been made by James Youngman . +*/ + + +#include "defs.h" + +#define USE_SAFE_CHDIR 1 +#undef STAT_MOUNTPOINTS + + +#include +#include + -#include -#include -#include -#include #ifdef HAVE_FCNTL_H #include #else #include #endif -#include "defs.h" -#include "modetype.h" -#ifndef S_IFLNK -#define lstat stat +#ifdef HAVE_SYS_UTSNAME_H +#include #endif -int lstat (); -int stat (); +#include "../gnulib/lib/xalloc.h" +#include "../gnulib/lib/human.h" +#include "../gnulib/lib/canonicalize.h" +#include "closein.h" +#include +#include "savedirinfo.h" +#include "buildcmd.h" +#include "dirname.h" +#include "quote.h" +#include "quotearg.h" + +#ifdef HAVE_LOCALE_H +#include +#endif + +#if ENABLE_NLS +# include +# define _(Text) gettext (Text) +#else +# define _(Text) Text +#define textdomain(Domain) +#define bindtextdomain(Package, Directory) +#endif +#ifdef gettext_noop +# define N_(String) gettext_noop (String) +#else +/* See locate.c for explanation as to why not use (String) */ +# define N_(String) String +#endif #define apply_predicate(pathname, stat_buf_ptr, node) \ (*(node)->pred_func)((pathname), (stat_buf_ptr), (node)) -static void process_top_path P_((char *pathname)); -static int process_path P_((char *pathname, char *name, boolean leaf, char *parent)); -static void process_dir P_((char *pathname, char *name, int pathlen, struct stat *statp, char *parent)); -static boolean no_side_effects P_((struct predicate *pred)); +#ifdef STAT_MOUNTPOINTS +static void init_mounted_dev_list(int mandatory); +#endif + +static void process_top_path PARAMS((char *pathname, mode_t mode)); +static int process_path PARAMS((char *pathname, char *name, boolean leaf, char *parent, mode_t type)); +static void process_dir PARAMS((char *pathname, char *name, int pathlen, struct stat *statp, char *parent)); + +static void complete_pending_execdirs(struct predicate *p); +static void complete_pending_execs (struct predicate *p); + + + +static boolean default_prints PARAMS((struct predicate *pred)); /* Name this program was run with. */ char *program_name; @@ -59,136 +103,462 @@ struct predicate *predicates; struct predicate *last_pred; /* The root of the evaluation tree. */ -static struct predicate *eval_tree; +static struct predicate *eval_tree = NULL; -/* If true, process directory before contents. True unless -depth given. */ -boolean do_dir_first; -/* If >=0, don't descend more than this many levels of subdirectories. */ -int maxdepth; +struct options options; +struct state state; -/* If >=0, don't process files above this level. */ -int mindepth; +/* The full path of the initial working directory, or "." if + STARTING_DESC is nonnegative. */ +char const *starting_dir = "."; -/* Current depth; 0 means current path is a command line arg. */ -int curdepth; - -/* Seconds between 00:00 1/1/70 and either one day before now - (the default), or the start of today (if -daystart is given). */ -time_t cur_day_start; - -/* If true, cur_day_start has been adjusted to the start of the day. */ -boolean full_days; - -/* If true, do not assume that files in directories with nlink == 2 - are non-directories. */ -boolean no_leaf_check; - -/* If true, don't cross filesystem boundaries. */ -boolean stay_on_filesystem; - -/* If true, don't descend past current directory. - Can be set by -prune, -maxdepth, and -xdev/-mount. */ -boolean stop_at_current_level; - -#ifndef HAVE_FCHDIR -/* The full path of the initial working directory. */ -char *starting_dir; -#else /* A file descriptor open to the initial working directory. Doing it this way allows us to work when the i.w.d. has unreadable parents. */ int starting_desc; -#endif -/* If true, we have called stat on the current path. */ -boolean have_stat; +/* The stat buffer of the initial working directory. */ +struct stat starting_stat_buf; -/* The file being operated on, relative to the current directory. - Used for stat, readlink, and opendir. */ -char *rel_pathname; +enum ChdirSymlinkHandling + { + SymlinkHandleDefault, /* Normally the right choice */ + SymlinkFollowOk /* see comment in process_top_path() */ + }; -/* Length of current path. */ -int path_length; -/* true if following symlinks. Should be consistent with xstat. */ -boolean dereference; +enum TraversalDirection + { + TraversingUp, + TraversingDown + }; -/* Pointer to the function used to stat files. */ -int (*xstat) (); +enum WdSanityCheckFatality + { + FATAL_IF_SANITY_CHECK_FAILS, + RETRY_IF_SANITY_CHECK_FAILS, + NON_FATAL_IF_SANITY_CHECK_FAILS + }; -/* Status value to return to system. */ -int exit_status; - -#ifdef DEBUG_STAT -static int -debug_stat (file, bufp) - char *file; - struct stat *bufp; + +int +following_links(void) { + switch (options.symlink_handling) + { + case SYMLINK_ALWAYS_DEREF: + return 1; + case SYMLINK_DEREF_ARGSONLY: + return (state.curdepth == 0); + case SYMLINK_NEVER_DEREF: + default: + return 0; + } +} + + +static int +fallback_stat(const char *name, struct stat *p, int prev_rv) +{ + /* Our original stat() call failed. Perhaps we can't follow a + * symbolic link. If that might be the problem, lstat() the link. + * Otherwise, admit defeat. + */ + switch (errno) + { + case ENOENT: + case ENOTDIR: +#ifdef DEBUG_STAT + fprintf(stderr, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name); +#endif + return lstat(name, p); + + case EACCES: + case EIO: + case ELOOP: + case ENAMETOOLONG: +#ifdef EOVERFLOW + case EOVERFLOW: /* EOVERFLOW is not #defined on UNICOS. */ +#endif + default: + return prev_rv; + } +} + + +/* optionh_stat() implements the stat operation when the -H option is + * in effect. + * + * If the item to be examined is a command-line argument, we follow + * symbolic links. If the stat() call fails on the command-line item, + * we fall back on the properties of the symbolic link. + * + * If the item to be examined is not a command-line argument, we + * examine the link itself. + */ +int +optionh_stat(const char *name, struct stat *p) +{ + if (0 == state.curdepth) + { + /* This file is from the command line; deference the link (if it + * is a link). + */ + int rv = stat(name, p); + if (0 == rv) + return 0; /* success */ + else + return fallback_stat(name, p, rv); + } + else + { + /* Not a file on the command line; do not dereference the link. + */ + return lstat(name, p); + } +} + +/* optionl_stat() implements the stat operation when the -L option is + * in effect. That option makes us examine the thing the symbolic + * link points to, not the symbolic link itself. + */ +int +optionl_stat(const char *name, struct stat *p) +{ + int rv = stat(name, p); + if (0 == rv) + return 0; /* normal case. */ + else + return fallback_stat(name, p, rv); +} + +/* optionp_stat() implements the stat operation when the -P option is + * in effect (this is also the default). That option makes us examine + * the symbolic link itself, not the thing it points to. + */ +int +optionp_stat(const char *name, struct stat *p) +{ + return lstat(name, p); +} + +#ifdef DEBUG_STAT +static uintmax_t stat_count = 0u; + +static int +debug_stat (const char *file, struct stat *bufp) +{ + ++stat_count; fprintf (stderr, "debug_stat (%s)\n", file); - return lstat (file, bufp); + switch (options.symlink_handling) + { + case SYMLINK_ALWAYS_DEREF: + return optionl_stat(file, bufp); + case SYMLINK_DEREF_ARGSONLY: + return optionh_stat(file, bufp); + case SYMLINK_NEVER_DEREF: + return optionp_stat(file, bufp); + } } #endif /* DEBUG_STAT */ -void -main (argc, argv) - int argc; - char *argv[]; +void +set_follow_state(enum SymlinkOption opt) +{ + switch (opt) + { + case SYMLINK_ALWAYS_DEREF: /* -L */ + options.xstat = optionl_stat; + options.no_leaf_check = true; + break; + + case SYMLINK_NEVER_DEREF: /* -P (default) */ + options.xstat = optionp_stat; + /* Can't turn no_leaf_check off because the user might have specified + * -noleaf anyway + */ + break; + + case SYMLINK_DEREF_ARGSONLY: /* -H */ + options.xstat = optionh_stat; + options.no_leaf_check = true; + } + + options.symlink_handling = opt; + + /* For DEBUG_STAT, the choice is made at runtime within debug_stat() + * by checking the contents of the symlink_handling variable. + */ +#if defined(DEBUG_STAT) + options.xstat = debug_stat; +#endif /* !DEBUG_STAT */ +} + + +/* Complete any outstanding commands. + */ +void +cleanup(void) +{ + if (eval_tree) + { + complete_pending_execs(eval_tree); + complete_pending_execdirs(eval_tree); + } +} + +/* Get the stat information for a file, if it is + * not already known. + */ +int +get_statinfo (const char *pathname, const char *name, struct stat *p) +{ + if (!state.have_stat && (*options.xstat) (name, p) != 0) + { + if (!options.ignore_readdir_race || (errno != ENOENT) ) + { + error (0, errno, "%s", pathname); + state.exit_status = 1; + } + return -1; + } + state.have_stat = true; + state.have_type = true; + state.type = p->st_mode; + return 0; +} + +/* Get the stat/type information for a file, if it is + * not already known. + */ +int +get_info (const char *pathname, + const char *name, + struct stat *p, + struct predicate *pred_ptr) +{ + /* If we need the full stat info, or we need the type info but don't + * already have it, stat the file now. + */ + (void) name; + if (pred_ptr->need_stat) + { + return get_statinfo(pathname, state.rel_pathname, p); + } + if ((pred_ptr->need_type && (0 == state.have_type))) + { + return get_statinfo(pathname, state.rel_pathname, p); + } + return 0; +} + +/* Determine if we can use O_NOFOLLOW. + */ +#if defined(O_NOFOLLOW) +static boolean +check_nofollow(void) +{ + struct utsname uts; + float release; + + if (0 == uname(&uts)) + { + /* POSIX requires that atof() ignore "unrecognised suffixes". */ + release = atof(uts.release); + + if (0 == strcmp("Linux", uts.sysname)) + { + /* Linux kernels 2.1.126 and earlier ignore the O_NOFOLLOW flag. */ + return release >= 2.2; /* close enough */ + } + else if (0 == strcmp("FreeBSD", uts.sysname)) + { + /* FreeBSD 3.0-CURRENT and later support it */ + return release >= 3.1; + } + } + + /* Well, O_NOFOLLOW was defined, so we'll try to use it. */ + return true; +} +#endif + +int +main (int argc, char **argv) { int i; - PFB parse_function; /* Pointer to who is to do the parsing. */ + const struct parser_table *entry_close, *entry_print, *entry_open; + const struct parser_table *parse_entry; /* Pointer to the parsing table entry for this expression. */ struct predicate *cur_pred; char *predicate_name; /* Name of predicate being parsed. */ + int end_of_leading_options = 0; /* First arg after any -H/-L etc. */ + program_name = argv[0]; + /* We call check_nofollow() before setlocale() because the numbers + * for which we check (in the results of uname) definitiely have "." + * as the decimal point indicator even under locales for which that + * is not normally true. Hence atof() would do the wrong thing + * if we call it after setlocale(). + */ +#ifdef O_NOFOLLOW + options.open_nofollow_available = check_nofollow(); +#else + options.open_nofollow_available = false; +#endif + + options.regex_options = RE_SYNTAX_EMACS; + +#ifdef HAVE_SETLOCALE + setlocale (LC_ALL, ""); +#endif + bindtextdomain (PACKAGE, LOCALEDIR); + textdomain (PACKAGE); + atexit (close_stdin); + + + if (isatty(0)) + { + options.warnings = true; + } + else + { + options.warnings = false; + } + + predicates = NULL; last_pred = NULL; - do_dir_first = true; - maxdepth = mindepth = -1; - cur_day_start = time ((time_t *) 0) - DAYSECS; - full_days = false; - no_leaf_check = false; - stay_on_filesystem = false; - exit_status = 0; - dereference = false; -#ifdef DEBUG_STAT - xstat = debug_stat; -#else /* !DEBUG_STAT */ - xstat = lstat; + options.do_dir_first = true; + options.maxdepth = options.mindepth = -1; + options.start_time = time (NULL); + options.cur_day_start = options.start_time - DAYSECS; + options.full_days = false; + options.stay_on_filesystem = false; + options.ignore_readdir_race = false; + + state.exit_status = 0; + +#if defined(DEBUG_STAT) + options.xstat = debug_stat; #endif /* !DEBUG_STAT */ + if (getenv("POSIXLY_CORRECT")) + options.output_block_size = 512; + else + options.output_block_size = 1024; + + if (getenv("FIND_BLOCK_SIZE")) + { + error (1, 0, _("The environment variable FIND_BLOCK_SIZE is not supported, the only thing that affects the block size is the POSIXLY_CORRECT environment variable")); + } + +#if LEAF_OPTIMISATION + /* The leaf optimisation is enabled. */ + options.no_leaf_check = false; +#else + /* The leaf optimisation is disabled. */ + options.no_leaf_check = true; +#endif + + set_follow_state(SYMLINK_NEVER_DEREF); /* The default is equivalent to -P. */ + #ifdef DEBUG - printf ("cur_day_start = %s", ctime (&cur_day_start)); + fprintf (stderr, "cur_day_start = %s", ctime (&options.cur_day_start)); #endif /* DEBUG */ - /* Find where in ARGV the predicates begin. */ - for (i = 1; i < argc && strchr ("-!(),", argv[i][0]) == NULL; i++) - /* Do nothing. */ ; + /* Check for -P, -H or -L options. */ + for (i=1; (end_of_leading_options = i) < argc; ++i) + { + if (0 == strcmp("-H", argv[i])) + { + /* Meaning: dereference symbolic links on command line, but nowhere else. */ + set_follow_state(SYMLINK_DEREF_ARGSONLY); + } + else if (0 == strcmp("-L", argv[i])) + { + /* Meaning: dereference all symbolic links. */ + set_follow_state(SYMLINK_ALWAYS_DEREF); + } + else if (0 == strcmp("-P", argv[i])) + { + /* Meaning: never dereference symbolic links (default). */ + set_follow_state(SYMLINK_NEVER_DEREF); + } + else if (0 == strcmp("--", argv[i])) + { + /* -- signifies the end of options. */ + end_of_leading_options = i+1; /* Next time start with the next option */ + break; + } + else + { + /* Hmm, must be one of + * (a) A path name + * (b) A predicate + */ + end_of_leading_options = i; /* Next time start with this option */ + break; + } + } + /* We are now processing the part of the "find" command line + * after the -H/-L options (if any). + */ + + /* fprintf(stderr, "rest: optind=%ld\n", (long)optind); */ + + /* Find where in ARGV the predicates begin. */ + for (i = end_of_leading_options; i < argc && strchr ("-!(),", argv[i][0]) == NULL; i++) + { + /* fprintf(stderr, "Looks like %s is not a predicate\n", argv[i]); */ + /* Do nothing. */ ; + } + /* Enclose the expression in `( ... )' so a default -print will apply to the whole expression. */ - parse_open (argv, &argc); + entry_open = find_parser("("); + entry_close = find_parser(")"); + entry_print = find_parser("print"); + assert(entry_open != NULL); + assert(entry_close != NULL); + assert(entry_print != NULL); + + parse_openparen (entry_open, argv, &argc); + parse_begin_user_args(argv, argc, last_pred, predicates); + pred_sanity_check(last_pred); + /* Build the input order list. */ while (i < argc) { if (strchr ("-!(),", argv[i][0]) == NULL) - usage ("paths must precede expression"); + usage (_("paths must precede expression")); predicate_name = argv[i]; - parse_function = find_parser (predicate_name); - if (parse_function == NULL) - error (1, 0, "invalid predicate `%s'", predicate_name); + parse_entry = find_parser (predicate_name); + if (parse_entry == NULL) + { + /* Command line option not recognized */ + error (1, 0, _("invalid predicate `%s'"), predicate_name); + } + i++; - if (!(*parse_function) (argv, &i)) + if (!(*(parse_entry->parser_func)) (parse_entry, argv, &i)) { if (argv[i] == NULL) - error (1, 0, "missing argument to `%s'", predicate_name); + /* Command line option requires an argument */ + error (1, 0, _("missing argument to `%s'"), predicate_name); else - error (1, 0, "invalid argument `%s' to `%s'", + error (1, 0, _("invalid argument `%s' to `%s'"), argv[i], predicate_name); } + + pred_sanity_check(last_pred); + pred_sanity_check(predicates); /* XXX: expensive */ } + parse_end_user_args(argv, argc, last_pred, predicates); + if (predicates->pred_next == NULL) { /* No predicates that do something other than set a global variable @@ -196,34 +566,52 @@ main (argc, argv) cur_pred = predicates; predicates = last_pred = predicates->pred_next; free ((char *) cur_pred); - parse_print (argv, &argc); + parse_print (entry_print, argv, &argc); + pred_sanity_check(last_pred); + pred_sanity_check(predicates); /* XXX: expensive */ } - else if (!no_side_effects (predicates->pred_next)) + else if (!default_prints (predicates->pred_next)) { /* One or more predicates that produce output were given; remove the unneeded initial `('. */ cur_pred = predicates; predicates = predicates->pred_next; + pred_sanity_check(predicates); /* XXX: expensive */ free ((char *) cur_pred); } else { /* `( user-supplied-expression ) -print'. */ - parse_close (argv, &argc); - parse_print (argv, &argc); + parse_closeparen (entry_close, argv, &argc); + pred_sanity_check(last_pred); + parse_print (entry_print, argv, &argc); + pred_sanity_check(last_pred); + pred_sanity_check(predicates); /* XXX: expensive */ } #ifdef DEBUG - printf ("Predicate List:\n"); - print_list (predicates); + fprintf (stderr, "Predicate List:\n"); + print_list (stderr, predicates); #endif /* DEBUG */ + /* do a sanity check */ + pred_sanity_check(predicates); + /* Done parsing the predicates. Build the evaluation tree. */ cur_pred = predicates; eval_tree = get_expr (&cur_pred, NO_PREC); + + /* Check if we have any left-over predicates (this fixes + * Debian bug #185202). + */ + if (cur_pred != NULL) + { + error (1, 0, _("unexpected extra predicate")); + } + #ifdef DEBUG - printf ("Eval Tree:\n"); - print_tree (eval_tree, 0); + fprintf (stderr, "Eval Tree:\n"); + print_tree (stderr, eval_tree, 0); #endif /* DEBUG */ /* Rearrange the eval tree in optimal-predicate order. */ @@ -231,74 +619,888 @@ main (argc, argv) /* Determine the point, if any, at which to stat the file. */ mark_stat (eval_tree); + /* Determine the point, if any, at which to determine file type. */ + mark_type (eval_tree); #ifdef DEBUG - printf ("Optimized Eval Tree:\n"); - print_tree (eval_tree, 0); + fprintf (stderr, "Optimized Eval Tree:\n"); + print_tree (stderr, eval_tree, 0); + fprintf (stderr, "Optimized command line:\n"); + print_optlist(stderr, eval_tree); + fprintf(stderr, "\n"); #endif /* DEBUG */ -#ifndef HAVE_FCHDIR - starting_dir = xgetcwd (); - if (starting_dir == NULL) - error (1, errno, "cannot get current directory"); -#else - starting_desc = open (".", O_RDONLY); - if (starting_desc < 0) - error (1, errno, "cannot open current directory"); -#endif - - /* If no paths are given, default to ".". */ - for (i = 1; i < argc && strchr ("-!(),", argv[i][0]) == NULL; i++) - process_top_path (argv[i]); - if (i == 1) - process_top_path ("."); - - exit (exit_status); -} - -/* Descend PATHNAME, which is a command-line argument. */ - -static void -process_top_path (pathname) - char *pathname; -{ - struct stat stat_buf; - - curdepth = 0; - path_length = strlen (pathname); - - /* We stat each pathname given on the command-line twice -- - once here and once in process_path. It's not too bad, though, - since the kernel can read the stat information out of its inode - cache the second time. */ - if ((*xstat) (pathname, &stat_buf) == 0 && S_ISDIR (stat_buf.st_mode)) + /* safely_chdir() needs to check that it has ended up in the right place. + * To avoid bailing out when something gets automounted, it checks if + * the target directory appears to have had a directory mounted on it as + * we chdir()ed. The problem with this is that in order to notice that + * a filesystem was mounted, we would need to lstat() all the mount points. + * That strategy loses if our machine is a client of a dead NFS server. + * + * Hence if safely_chdir() and wd_sanity_check() can manage without needing + * to know the mounted device list, we do that. + */ + if (!options.open_nofollow_available) { - if (chdir (pathname) < 0) - { - error (0, errno, "%s", pathname); - exit_status = 1; - return; - } - process_path (pathname, ".", false, "."); -#ifndef HAVE_FCHDIR - if (chdir (starting_dir) < 0) - error (1, errno, "%s", starting_dir); -#else - if (fchdir (starting_desc)) - error (1, errno, "cannot return to starting directory"); +#ifdef STAT_MOUNTPOINTS + init_mounted_dev_list(0); #endif } - else - process_path (pathname, pathname, false, "."); + + + starting_desc = open (".", O_RDONLY); + if (0 <= starting_desc && fchdir (starting_desc) != 0) + { + close (starting_desc); + starting_desc = -1; + } + if (starting_desc < 0) + { + starting_dir = xgetcwd (); + if (! starting_dir) + error (1, errno, _("cannot get current directory")); + } + if ((*options.xstat) (".", &starting_stat_buf) != 0) + error (1, errno, _("cannot get current directory")); + + /* If no paths are given, default to ".". */ + for (i = end_of_leading_options; i < argc && strchr ("-!(),", argv[i][0]) == NULL; i++) + { + process_top_path (argv[i], 0); + } + + /* If there were no path arguments, default to ".". */ + if (i == end_of_leading_options) + { + /* + * We use a temporary variable here because some actions modify + * the path temporarily. Hence if we use a string constant, + * we get a coredump. The best example of this is if we say + * "find -printf %H" (note, not "find . -printf %H"). + */ + char defaultpath[2] = "."; + process_top_path (defaultpath, 0); + } + + /* If "-exec ... {} +" has been used, there may be some + * partially-full command lines which have been built, + * but which are not yet complete. Execute those now. + */ + cleanup(); + return state.exit_status; } + +static char * +specific_dirname(const char *dir) +{ + char dirbuf[1024]; + + if (0 == strcmp(".", dir)) + { + /* OK, what's '.'? */ + if (NULL != getcwd(dirbuf, sizeof(dirbuf))) + { + return strdup(dirbuf); + } + else + { + return strdup(dir); + } + } + else + { + char *result = canonicalize_filename_mode(dir, CAN_EXISTING); + if (NULL == result) + return strdup(dir); + else + return result; + } +} + + + +/* Return non-zero if FS is the name of a filesystem that is likely to + * be automounted + */ +static int +fs_likely_to_be_automounted(const char *fs) +{ + return ( (0==strcmp(fs, "nfs")) || (0==strcmp(fs, "autofs")) || (0==strcmp(fs, "subfs"))); +} + + + +#ifdef STAT_MOUNTPOINTS +static dev_t *mounted_devices = NULL; +static size_t num_mounted_devices = 0u; + + +static void +init_mounted_dev_list(int mandatory) +{ + assert(NULL == mounted_devices); + assert(0 == num_mounted_devices); + mounted_devices = get_mounted_devices(&num_mounted_devices); + if (mandatory && (NULL == mounted_devices)) + { + error(1, 0, "Cannot read list of mounted devices."); + } +} + +static void +refresh_mounted_dev_list(void) +{ + if (mounted_devices) + { + free(mounted_devices); + mounted_devices = 0; + } + num_mounted_devices = 0u; + init_mounted_dev_list(1); +} + + +/* Search for device DEV in the array LIST, which is of size N. */ +static int +dev_present(dev_t dev, const dev_t *list, size_t n) +{ + if (list) + { + while (n-- > 0u) + { + if ( (*list++) == dev ) + return 1; + } + } + return 0; +} + +enum MountPointStateChange + { + MountPointRecentlyMounted, + MountPointRecentlyUnmounted, + MountPointStateUnchanged + }; + + + +static enum MountPointStateChange +get_mount_state(dev_t newdev) +{ + int new_is_present, new_was_present; + + new_was_present = dev_present(newdev, mounted_devices, num_mounted_devices); + refresh_mounted_dev_list(); + new_is_present = dev_present(newdev, mounted_devices, num_mounted_devices); + + if (new_was_present == new_is_present) + return MountPointStateUnchanged; + else if (new_is_present) + return MountPointRecentlyMounted; + else + return MountPointRecentlyUnmounted; +} + + + +/* We stat()ed a directory, chdir()ed into it (we know this + * since direction is TraversingDown), stat()ed it again, + * and noticed that the device numbers are different. Check + * if the filesystem was recently mounted. + * + * If it was, it looks like chdir()ing into the directory + * caused a filesystem to be mounted. Maybe automount is + * running. Anyway, that's probably OK - but it happens + * only when we are moving downward. + * + * We also allow for the possibility that a similar thing + * has happened with the unmounting of a filesystem. This + * is much rarer, as it relies on an automounter timeout + * occurring at exactly the wrong moment. + */ +static enum WdSanityCheckFatality +dirchange_is_fatal(const char *specific_what, + enum WdSanityCheckFatality isfatal, + int silent, + struct stat *newinfo) +{ + enum MountPointStateChange transition = get_mount_state(newinfo->st_dev); + switch (transition) + { + case MountPointRecentlyUnmounted: + isfatal = NON_FATAL_IF_SANITY_CHECK_FAILS; + if (!silent) + { + error (0, 0, + _("Warning: filesystem %s has recently been unmounted."), + specific_what); + } + break; + + case MountPointRecentlyMounted: + isfatal = NON_FATAL_IF_SANITY_CHECK_FAILS; + if (!silent) + { + error (0, 0, + _("Warning: filesystem %s has recently been mounted."), + specific_what); + } + break; + + case MountPointStateUnchanged: + /* leave isfatal as it is */ + break; + } + + return isfatal; +} + + +#endif + + + +/* Examine the results of the stat() of a directory from before we + * entered or left it, with the results of stat()ing it afterward. If + * these are different, the filesystem tree has been modified while we + * were traversing it. That might be an attempt to use a race + * condition to persuade find to do something it didn't intend + * (e.g. an attempt by an ordinary user to exploit the fact that root + * sometimes runs find on the whole filesystem). However, this can + * also happen if automount is running (certainly on Solaris). With + * automount, moving into a directory can cause a filesystem to be + * mounted there. + * + * To cope sensibly with this, we will raise an error if we see the + * device number change unless we are chdir()ing into a subdirectory, + * and the directory we moved into has been mounted or unmounted "recently". + * Here "recently" means since we started "find" or we last re-read + * the /etc/mnttab file. + * + * If the device number does not change but the inode does, that is a + * problem. + * + * If the device number and inode are both the same, we are happy. + * + * If a filesystem is (un)mounted as we chdir() into the directory, that + * may mean that we're now examining a section of the filesystem that might + * have been excluded from consideration (via -prune or -quit for example). + * Hence we print a warning message to indicate that the output of find + * might be inconsistent due to the change in the filesystem. + */ +static boolean +wd_sanity_check(const char *thing_to_stat, + const char *progname, + const char *what, + dev_t old_dev, + ino_t old_ino, + struct stat *newinfo, + int parent, + int line_no, + enum TraversalDirection direction, + enum WdSanityCheckFatality isfatal, + boolean *changed) /* output parameter */ +{ + const char *fstype; + char *specific_what = NULL; + int silent = 0; + const char *current_dir = "."; + + *changed = false; + + if ((*options.xstat) (current_dir, newinfo) != 0) + error (1, errno, "%s", thing_to_stat); + + if (old_dev != newinfo->st_dev) + { + *changed = true; + specific_what = specific_dirname(what); + fstype = filesystem_type(newinfo, current_dir); + silent = fs_likely_to_be_automounted(fstype); + + /* This condition is rare, so once we are here it is + * reasonable to perform an expensive computation to + * determine if we should continue or fail. + */ + if (TraversingDown == direction) + { +#ifdef STAT_MOUNTPOINTS + isfatal = dirchange_is_fatal(specific_what,isfatal,silent,newinfo); +#else + isfatal = RETRY_IF_SANITY_CHECK_FAILS; +#endif + } + + switch (isfatal) + { + case FATAL_IF_SANITY_CHECK_FAILS: + { + fstype = filesystem_type(newinfo, current_dir); + error (1, 0, + _("%s%s changed during execution of %s (old device number %ld, new device number %ld, filesystem type is %s) [ref %ld]"), + specific_what, + parent ? "/.." : "", + progname, + (long) old_dev, + (long) newinfo->st_dev, + fstype, + line_no); + /*NOTREACHED*/ + return false; + } + + case NON_FATAL_IF_SANITY_CHECK_FAILS: + { + /* Since the device has changed under us, the inode number + * will almost certainly also be different. However, we have + * already decided that this is not a problem. Hence we return + * without checking the inode number. + */ + free(specific_what); + return true; + } + + case RETRY_IF_SANITY_CHECK_FAILS: + return false; + } + } + + /* Device number was the same, check if the inode has changed. */ + if (old_ino != newinfo->st_ino) + { + *changed = true; + specific_what = specific_dirname(what); + fstype = filesystem_type(newinfo, current_dir); + + error ((isfatal == FATAL_IF_SANITY_CHECK_FAILS) ? 1 : 0, + 0, /* no relevant errno value */ + _("%s%s changed during execution of %s (old inode number %ld, new inode number %ld, filesystem type is %s) [ref %ld]"), + specific_what, + parent ? "/.." : "", + progname, + (long) old_ino, + (long) newinfo->st_ino, + fstype, + line_no); + free(specific_what); + return false; + } + + return true; +} + +enum SafeChdirStatus + { + SafeChdirOK, + SafeChdirFailSymlink, + SafeChdirFailNotDir, + SafeChdirFailStat, + SafeChdirFailWouldBeUnableToReturn, + SafeChdirFailChdirFailed, + SafeChdirFailNonexistent, + SafeChdirFailDestUnreadable + }; + +/* Safely perform a change in directory. We do this by calling + * lstat() on the subdirectory, using chdir() to move into it, and + * then lstat()ing ".". We compare the results of the two stat calls + * to see if they are consistent. If not, we sound the alarm. + * + * If following_links() is true, we do follow symbolic links. + */ +static enum SafeChdirStatus +safely_chdir_lstat(const char *dest, + enum TraversalDirection direction, + struct stat *statbuf_dest, + enum ChdirSymlinkHandling symlink_follow_option, + boolean *did_stat) +{ + struct stat statbuf_arrived; + int rv, dotfd=-1; + int saved_errno; /* specific_dirname() changes errno. */ + boolean rv_set = false; + boolean statflag = false; + int tries = 0; + enum WdSanityCheckFatality isfatal = RETRY_IF_SANITY_CHECK_FAILS; + + saved_errno = errno = 0; + + dotfd = open(".", O_RDONLY); + + /* We jump back to here if wd_sanity_check() + * recoverably triggers an alert. + */ + retry: + ++tries; + + if (dotfd >= 0) + { + /* Stat the directory we're going to. */ + if (0 == options.xstat(dest, statbuf_dest)) + { + statflag = true; + +#ifdef S_ISLNK + /* symlink_follow_option might be set to SymlinkFollowOk, which + * would allow us to chdir() into a symbolic link. This is + * only useful for the case where the directory we're + * chdir()ing into is the basename of a command line + * argument, for example where "foo/bar/baz" is specified on + * the command line. When -P is in effect (the default), + * baz will not be followed if it is a symlink, but if bar + * is a symlink, it _should_ be followed. Hence we need the + * ability to override the policy set by following_links(). + */ + if (!following_links() && S_ISLNK(statbuf_dest->st_mode)) + { + /* We're not supposed to be following links, but this is + * a link. Check symlink_follow_option to see if we should + * make a special exception. + */ + if (symlink_follow_option == SymlinkFollowOk) + { + /* We need to re-stat() the file so that the + * sanity check can pass. + */ + if (0 != stat(dest, statbuf_dest)) + { + rv = SafeChdirFailNonexistent; + rv_set = true; + saved_errno = errno; + goto fail; + } + statflag = true; + } + else + { + /* Not following symlinks, so the attempt to + * chdir() into a symlink should be prevented. + */ + rv = SafeChdirFailSymlink; + rv_set = true; + saved_errno = 0; /* silence the error message */ + goto fail; + } + } +#endif +#ifdef S_ISDIR + /* Although the immediately following chdir() would detect + * the fact that this is not a directory for us, this would + * result in an extra system call that fails. Anybody + * examining the system-call trace should ideally not be + * concerned that something is actually failing. + */ + if (!S_ISDIR(statbuf_dest->st_mode)) + { + rv = SafeChdirFailNotDir; + rv_set = true; + saved_errno = 0; /* silence the error message */ + goto fail; + } +#endif +#ifdef DEBUG_STAT + fprintf(stderr, "safely_chdir(): chdir(\"%s\")\n", dest); +#endif + if (0 == chdir(dest)) + { + /* check we ended up where we wanted to go */ + boolean changed = false; + if (!wd_sanity_check(".", program_name, ".", + statbuf_dest->st_dev, + statbuf_dest->st_ino, + &statbuf_arrived, + 0, __LINE__, direction, + isfatal, + &changed)) + { + /* Only allow one failure. */ + if (RETRY_IF_SANITY_CHECK_FAILS == isfatal) + { + if (0 == fchdir(dotfd)) + { + isfatal = FATAL_IF_SANITY_CHECK_FAILS; + goto retry; + } + else + { + /* Failed to return to original directory, + * but we know that the current working + * directory is not the one that we intend + * to be in. Since fchdir() failed, we + * can't recover from this and so this error + * is fatal. + */ + error(1, errno, + "failed to return to parent directory"); + } + } + else + { + /* XXX: not sure what to use as an excuse here. */ + rv = SafeChdirFailNonexistent; + rv_set = true; + saved_errno = 0; + goto fail; + } + } + + close(dotfd); + return SafeChdirOK; + } + else + { + saved_errno = errno; + if (ENOENT == saved_errno) + { + rv = SafeChdirFailNonexistent; + rv_set = true; + if (options.ignore_readdir_race) + errno = 0; /* don't issue err msg */ + } + else if (ENOTDIR == saved_errno) + { + /* This can happen if the we stat a directory, + * and then filesystem activity changes it into + * a non-directory. + */ + saved_errno = 0; /* don't issue err msg */ + rv = SafeChdirFailNotDir; + rv_set = true; + } + else + { + rv = SafeChdirFailChdirFailed; + rv_set = true; + } + goto fail; + } + } + else + { + saved_errno = errno; + rv = SafeChdirFailStat; + rv_set = true; + + if ( (ENOENT == saved_errno) || (0 == state.curdepth)) + saved_errno = 0; /* don't issue err msg */ + goto fail; + } + } + else + { + /* We do not have read permissions on "." */ + rv = SafeChdirFailWouldBeUnableToReturn; + rv_set = true; + goto fail; + } + + /* This is the success path, so we clear errno. The caller probably + * won't be calling error() anyway. + */ + saved_errno = 0; + + /* We use the same exit path for success or failure. + * which has occurred is recorded in RV. + */ + fail: + /* We do not call error() as this would result in a duplicate error + * message when the caller does the same thing. + */ + if (saved_errno) + errno = saved_errno; + + if (dotfd >= 0) + { + close(dotfd); + dotfd = -1; + } + + *did_stat = statflag; + assert(rv_set); + return rv; +} + +#if defined(O_NOFOLLOW) +/* Safely change working directory to the specified subdirectory. If + * we are not allowed to follow symbolic links, we use open() with + * O_NOFOLLOW, followed by fchdir(). This ensures that we don't + * follow symbolic links (of course, we do follow them if the -L + * option is in effect). + */ +static enum SafeChdirStatus +safely_chdir_nofollow(const char *dest, + enum TraversalDirection direction, + struct stat *statbuf_dest, + enum ChdirSymlinkHandling symlink_follow_option, + boolean *did_stat) +{ + int extraflags, fd; + extraflags = 0; + + *did_stat = false; + + switch (symlink_follow_option) + { + case SymlinkFollowOk: + extraflags = 0; + break; + + case SymlinkHandleDefault: + if (following_links()) + extraflags = 0; + else + extraflags = O_NOFOLLOW; + break; + } + + errno = 0; + fd = open(dest, O_RDONLY|extraflags); + if (fd < 0) + { + switch (errno) + { + case ELOOP: + return SafeChdirFailSymlink; /* This is why we use O_NOFOLLOW */ + case ENOENT: + return SafeChdirFailNonexistent; + default: + return SafeChdirFailDestUnreadable; + } + } + + errno = 0; + if (0 == fchdir(fd)) + { + close(fd); + return SafeChdirOK; + } + else + { + int saved_errno = errno; + close(fd); + errno = saved_errno; + + switch (errno) + { + case ENOTDIR: + return SafeChdirFailNotDir; + + case EACCES: + case EBADF: /* Shouldn't happen */ + case EINTR: + case EIO: + default: + return SafeChdirFailChdirFailed; + } + } +} +#endif + +static enum SafeChdirStatus +safely_chdir(const char *dest, + enum TraversalDirection direction, + struct stat *statbuf_dest, + enum ChdirSymlinkHandling symlink_follow_option, + boolean *did_stat) +{ + /* We're about to leave a directory. If there are any -execdir + * argument lists which have been built but have not yet been + * processed, do them now because they must be done in the same + * directory. + */ + complete_pending_execdirs(eval_tree); + +#if defined(O_NOFOLLOW) + if (options.open_nofollow_available) + { + enum SafeChdirStatus result; + result = safely_chdir_nofollow(dest, direction, statbuf_dest, + symlink_follow_option, did_stat); + if (SafeChdirFailDestUnreadable != result) + { + return result; + } + else + { + /* Savannah bug #15384: fall through to use safely_chdir_lstat + * if the directory is not readable. + */ + /* Do nothing. */ + } + } +#endif + /* Even if O_NOFOLLOW is available, we may need to use the alternative + * method, since parent of the start point may be executable but not + * readable. + */ + return safely_chdir_lstat(dest, direction, statbuf_dest, + symlink_follow_option, did_stat); +} + + + +/* Safely go back to the starting directory. */ +static void +chdir_back (void) +{ + struct stat stat_buf; + boolean dummy; + + if (starting_desc < 0) + { +#ifdef DEBUG_STAT + fprintf(stderr, "chdir_back(): chdir(\"%s\")\n", starting_dir); +#endif + +#ifdef STAT_MOUNTPOINTS + /* We will need the mounted device list. Get it now if we don't + * already have it. + */ + if (NULL == mounted_devices) + init_mounted_dev_list(1); +#endif + + if (chdir (starting_dir) != 0) + error (1, errno, "%s", starting_dir); + + wd_sanity_check(starting_dir, + program_name, + starting_dir, + starting_stat_buf.st_dev, + starting_stat_buf.st_ino, + &stat_buf, 0, __LINE__, + TraversingUp, + FATAL_IF_SANITY_CHECK_FAILS, + &dummy); + } + else + { +#ifdef DEBUG_STAT + fprintf(stderr, "chdir_back(): chdir()\n"); +#endif + if (fchdir (starting_desc) != 0) + error (1, errno, "%s", starting_dir); + } +} + +/* Move to the parent of a given directory and then call a function, + * restoring the cwd. Don't bother changing directory if the + * specified directory is a child of "." or is the root directory. + */ +static void +at_top (char *pathname, + mode_t mode, + struct stat *pstat, + void (*action)(char *pathname, + char *basename, + int mode, + struct stat *pstat)) +{ + int dirchange; + char *parent_dir = dir_name (pathname); + char *base = last_component (pathname); + + state.curdepth = 0; + state.path_length = strlen (pathname); + + if (0 == *base + || 0 == strcmp(parent_dir, ".")) + { + dirchange = 0; + base = pathname; + } + else + { + enum TraversalDirection direction; + enum SafeChdirStatus chdir_status; + struct stat st; + boolean did_stat = false; + + dirchange = 1; + if (0 == strcmp(base, "..")) + direction = TraversingUp; + else + direction = TraversingDown; + + /* We pass SymlinkFollowOk to safely_chdir(), which allows it to + * chdir() into a symbolic link. This is only useful for the + * case where the directory we're chdir()ing into is the + * basename of a command line argument, for example where + * "foo/bar/baz" is specified on the command line. When -P is + * in effect (the default), baz will not be followed if it is a + * symlink, but if bar is a symlink, it _should_ be followed. + * Hence we need the ability to override the policy set by + * following_links(). + */ + chdir_status = safely_chdir(parent_dir, direction, &st, SymlinkFollowOk, &did_stat); + if (SafeChdirOK != chdir_status) + { + const char *what = (SafeChdirFailWouldBeUnableToReturn == chdir_status) ? "." : parent_dir; + if (errno) + error (0, errno, "%s", what); + else + error (0, 0, "Failed to safely change directory into `%s'", + parent_dir); + + /* We can't process this command-line argument. */ + state.exit_status = 1; + return; + } + } + + free (parent_dir); + parent_dir = NULL; + + action(pathname, base, mode, pstat); + + if (dirchange) + { + chdir_back(); + } +} + + +static void do_process_top_dir(char *pathname, + char *base, + int mode, + struct stat *pstat) +{ + process_path (pathname, base, false, ".", mode); + complete_pending_execdirs(eval_tree); +} + +static void do_process_predicate(char *pathname, + char *base, + int mode, + struct stat *pstat) +{ + state.rel_pathname = base; + apply_predicate (pathname, pstat, eval_tree); +} + + + + +/* Descend PATHNAME, which is a command-line argument. + + Actions like -execdir assume that we are in the + parent directory of the file we're examining, + and on entry to this function our working directory + is whatever it was when find was invoked. Therefore + If PATHNAME is "." we just leave things as they are. + Otherwise, we figure out what the parent directory is, + and move to that. +*/ +static void +process_top_path (char *pathname, mode_t mode) +{ + at_top(pathname, mode, NULL, do_process_top_dir); +} + + /* Info on each directory in the current tree branch, to avoid getting stuck in symbolic link loops. */ -struct dir_id -{ - ino_t ino; - dev_t dev; -}; static struct dir_id *dir_ids = NULL; /* Entries allocated in `dir_ids'. */ static int dir_alloc = 0; @@ -308,6 +1510,114 @@ static int dir_curr = -1; /* (Arbitrary) number of entries to grow `dir_ids' by. */ #define DIR_ALLOC_STEP 32 + + +/* We've detected a filesystem loop. This is caused by one of + * two things: + * + * 1. Option -L is in effect and we've hit a symbolic link that + * points to an ancestor. This is harmless. We won't traverse the + * symbolic link. + * + * 2. We have hit a real cycle in the directory hierarchy. In this + * case, we issue a diagnostic message (POSIX requires this) and we + * skip that directory entry. + */ +static void +issue_loop_warning(const char *name, const char *pathname, int level) +{ + struct stat stbuf_link; + if (lstat(name, &stbuf_link) != 0) + stbuf_link.st_mode = S_IFREG; + + if (S_ISLNK(stbuf_link.st_mode)) + { + error(0, 0, + _("Symbolic link `%s' is part of a loop in the directory hierarchy; we have already visited the directory to which it points."), + pathname); + } + else + { + int distance = 1 + (dir_curr-level); + /* We have found an infinite loop. POSIX requires us to + * issue a diagnostic. Usually we won't get to here + * because when the leaf optimisation is on, it will cause + * the subdirectory to be skipped. If /a/b/c/d is a hard + * link to /a/b, then the link count of /a/b/c is 2, + * because the ".." entry of /b/b/c/d points to /a, not + * to /a/b/c. + */ + error(0, 0, + _("Filesystem loop detected; `%s' has the same device number and inode as a directory which is %d %s."), + pathname, + distance, + (distance == 1 ? + _("level higher in the filesystem hierarchy") : + _("levels higher in the filesystem hierarchy"))); + } +} + +/* Take a "mode" indicator and fill in the files of 'state'. + */ +static int +digest_mode(mode_t mode, + const char *pathname, + const char *name, + struct stat *pstat, + boolean leaf) +{ + /* If we know the type of the directory entry, and it is not a + * symbolic link, we may be able to avoid a stat() or lstat() call. + */ + if (mode) + { + if (S_ISLNK(mode) && following_links()) + { + /* mode is wrong because we should have followed the symlink. */ + if (get_statinfo(pathname, name, pstat) != 0) + return 0; + mode = state.type = pstat->st_mode; + state.have_type = true; + } + else + { + state.have_type = true; + pstat->st_mode = state.type = mode; + } + } + else + { + /* Mode is not yet known; may have to stat the file unless we + * can deduce that it is not a directory (which is all we need to + * know at this stage) + */ + if (leaf) + { + state.have_stat = false; + state.have_type = false;; + state.type = 0; + } + else + { + if (get_statinfo(pathname, name, pstat) != 0) + return 0; + + /* If -L is in effect and we are dealing with a symlink, + * st_mode is the mode of the pointed-to file, while mode is + * the mode of the directory entry (S_IFLNK). Hence now + * that we have the stat information, override "mode". + */ + state.type = pstat->st_mode; + state.have_type = true; + } + } + + /* success. */ + return 1; +} + + + /* Recursively descend path PATHNAME, applying the predicates. LEAF is true if PATHNAME is known to be in a directory that has no more unexamined subdirectories, and therefore it is not a directory. @@ -323,11 +1633,8 @@ static int dir_curr = -1; Return nonzero iff PATHNAME is a directory. */ static int -process_path (pathname, name, leaf, parent) - char *pathname; - char *name; - boolean leaf; - char *parent; +process_path (char *pathname, char *name, boolean leaf, char *parent, + mode_t mode) { struct stat stat_buf; static dev_t root_dev; /* Device ID of current argument pathname. */ @@ -335,40 +1642,46 @@ process_path (pathname, name, leaf, parent) /* Assume it is a non-directory initially. */ stat_buf.st_mode = 0; + state.rel_pathname = name; + state.type = 0; + state.have_stat = false; + state.have_type = false; - rel_pathname = name; - - if (leaf) - have_stat = false; - else + if (!digest_mode(mode, pathname, name, &stat_buf, leaf)) + return 0; + + if (!S_ISDIR (state.type)) { - if ((*xstat) (name, &stat_buf) != 0) - { - error (0, errno, "%s", pathname); - exit_status = 1; - return 0; - } - have_stat = true; - } - - if (!S_ISDIR (stat_buf.st_mode)) - { - if (curdepth >= mindepth) + if (state.curdepth >= options.mindepth) apply_predicate (pathname, &stat_buf, eval_tree); return 0; } /* From here on, we're working on a directory. */ - stop_at_current_level = maxdepth >= 0 && curdepth >= maxdepth; + + /* Now we really need to stat the directory, even if we know the + * type, because we need information like struct stat.st_rdev. + */ + if (get_statinfo(pathname, name, &stat_buf) != 0) + return 0; + + state.have_stat = true; + mode = state.type = stat_buf.st_mode; /* use full info now that we have it. */ + state.stop_at_current_level = + options.maxdepth >= 0 + && state.curdepth >= options.maxdepth; /* If we've already seen this directory on this branch, don't descend it again. */ for (i = 0; i <= dir_curr; i++) if (stat_buf.st_ino == dir_ids[i].ino && stat_buf.st_dev == dir_ids[i].dev) - stop_at_current_level = true; - + { + state.stop_at_current_level = true; + issue_loop_warning(name, pathname, i); + } + if (dir_alloc <= ++dir_curr) { dir_alloc += DIR_ALLOC_STEP; @@ -378,28 +1691,126 @@ process_path (pathname, name, leaf, parent) dir_ids[dir_curr].ino = stat_buf.st_ino; dir_ids[dir_curr].dev = stat_buf.st_dev; - if (stay_on_filesystem) + if (options.stay_on_filesystem) { - if (curdepth == 0) + if (state.curdepth == 0) root_dev = stat_buf.st_dev; else if (stat_buf.st_dev != root_dev) - stop_at_current_level = true; + state.stop_at_current_level = true; } - if (do_dir_first && curdepth >= mindepth) + if (options.do_dir_first && state.curdepth >= options.mindepth) apply_predicate (pathname, &stat_buf, eval_tree); - if (stop_at_current_level == false) +#ifdef DEBUG + fprintf(stderr, "pathname = %s, stop_at_current_level = %d\n", + pathname, state.stop_at_current_level); +#endif /* DEBUG */ + + if (state.stop_at_current_level == false) /* Scan directory on disk. */ process_dir (pathname, name, strlen (pathname), &stat_buf, parent); - if (do_dir_first == false && curdepth >= mindepth) - apply_predicate (pathname, &stat_buf, eval_tree); + if (options.do_dir_first == false && state.curdepth >= options.mindepth) + { + /* The fields in 'state' are now out of date. Correct them. + */ + if (!digest_mode(mode, pathname, name, &stat_buf, leaf)) + return 0; + + if (0 == dir_curr) + { + at_top(pathname, mode, &stat_buf, do_process_predicate); + } + else + { + do_process_predicate(pathname, name, mode, &stat_buf); + } + } dir_curr--; return 1; } + +/* Examine the predicate list for instances of -execdir or -okdir + * which have been terminated with '+' (build argument list) rather + * than ';' (singles only). If there are any, run them (this will + * have no effect if there are no arguments waiting). + */ +static void +complete_pending_execdirs(struct predicate *p) +{ +#if defined(NEW_EXEC) + if (NULL == p) + return; + + complete_pending_execdirs(p->pred_left); + + if (p->pred_func == pred_execdir || p->pred_func == pred_okdir) + { + /* It's an exec-family predicate. p->args.exec_val is valid. */ + if (p->args.exec_vec.multiple) + { + struct exec_val *execp = &p->args.exec_vec; + + /* This one was terminated by '+' and so might have some + * left... Run it if necessary. + */ + if (execp->state.todo) + { + /* There are not-yet-executed arguments. */ + launch (&execp->ctl, &execp->state); + } + } + } + + complete_pending_execdirs(p->pred_right); +#else + /* nothing to do. */ + return; +#endif +} + +/* Examine the predicate list for instances of -exec which have been + * terminated with '+' (build argument list) rather than ';' (singles + * only). If there are any, run them (this will have no effect if + * there are no arguments waiting). + */ +static void +complete_pending_execs(struct predicate *p) +{ +#if defined(NEW_EXEC) + if (NULL == p) + return; + + complete_pending_execs(p->pred_left); + + /* It's an exec-family predicate then p->args.exec_val is valid + * and we can check it. + */ + if (p->pred_func == pred_exec && p->args.exec_vec.multiple) + { + struct exec_val *execp = &p->args.exec_vec; + + /* This one was terminated by '+' and so might have some + * left... Run it if necessary. Set state.exit_status if + * there are any problems. + */ + if (execp->state.todo) + { + /* There are not-yet-executed arguments. */ + launch (&execp->ctl, &execp->state); + } + } + + complete_pending_execs(p->pred_right); +#else + /* nothing to do. */ + return; +#endif +} + /* Scan directory PATHNAME and recurse through process_path for each entry. @@ -407,36 +1818,40 @@ process_path (pathname, name, leaf, parent) NAME is PATHNAME relative to the current directory. - STATP is the results of *xstat on it. + STATP is the results of *options.xstat on it. PARENT is the path of the parent of NAME, relative to find's starting directory. */ static void -process_dir (pathname, name, pathlen, statp, parent) - char *pathname; - char *name; - int pathlen; - struct stat *statp; - char *parent; +process_dir (char *pathname, char *name, int pathlen, struct stat *statp, char *parent) { - char *name_space; /* Names of files in PATHNAME. */ int subdirs_left; /* Number of unexamined subdirs in PATHNAME. */ + boolean subdirs_unreliable; /* if true, cannot use dir link count as subdir limif (if false, it may STILL be unreliable) */ + int idx; /* Which entry are we on? */ + struct stat stat_buf; - subdirs_left = statp->st_nlink - 2; /* Account for name and ".". */ + struct savedir_dirinfo *dirinfo; - errno = 0; - /* On some systems (VAX 4.3BSD+NFS), NFS mount points have st_size < 0. */ - name_space = savedir (name, statp->st_size > 0 ? statp->st_size : 512); - if (name_space == NULL) + if (statp->st_nlink < 2) { - if (errno) - { - error (0, errno, "%s", pathname); - exit_status = 1; - } - else - error (1, 0, "virtual memory exhausted"); + subdirs_unreliable = true; + } + else + { + subdirs_unreliable = false; /* not necessarily right */ + subdirs_left = statp->st_nlink - 2; /* Account for name and ".". */ + } + + errno = 0; + dirinfo = xsavedir(name, 0); + + + if (dirinfo == NULL) + { + assert(errno != 0); + error (0, errno, "%s", pathname); + state.exit_status = 1; } else { @@ -446,7 +1861,8 @@ process_dir (pathname, name, pathlen, statp, parent) unsigned cur_path_size; /* Bytes allocated for `cur_path'. */ register unsigned file_len; /* Length of each path to process. */ register unsigned pathname_len; /* PATHLEN plus trailing '/'. */ - + boolean did_stat = false; + if (pathname[pathlen - 1] == '/') pathname_len = pathlen + 1; /* For '\0'; already have '/'. */ else @@ -454,15 +1870,75 @@ process_dir (pathname, name, pathlen, statp, parent) cur_path_size = 0; cur_path = NULL; - if (strcmp (name, ".") && chdir (name) < 0) + /* We're about to leave the directory. If there are any + * -execdir argument lists which have been built but have not + * yet been processed, do them now because they must be done in + * the same directory. + */ + complete_pending_execdirs(eval_tree); + + if (strcmp (name, ".")) { - error (0, errno, "%s", pathname); - exit_status = 1; - return; + enum SafeChdirStatus status = safely_chdir (name, TraversingDown, &stat_buf, SymlinkHandleDefault, &did_stat); + switch (status) + { + case SafeChdirOK: + /* If there had been a change but wd_sanity_check() + * accepted it, we need to accept that on the + * way back up as well, so modify our record + * of what we think we should see later. + * If there was no change, the assignments are a no-op. + * + * However, before performing the assignment, we need to + * check that we have the stat information. If O_NOFOLLOW + * is available, safely_chdir() will not have needed to use + * stat(), and so stat_buf will just contain random data. + */ + if (!did_stat) + { + /* If there is a link we need to follow it. Hence + * the direct call to stat() not through (options.xstat) + */ + if (0 != stat(".", &stat_buf)) + break; /* skip the assignment. */ + } + dir_ids[dir_curr].dev = stat_buf.st_dev; + dir_ids[dir_curr].ino = stat_buf.st_ino; + + break; + + case SafeChdirFailWouldBeUnableToReturn: + error (0, errno, "."); + state.exit_status = 1; + break; + + case SafeChdirFailNonexistent: + case SafeChdirFailDestUnreadable: + case SafeChdirFailStat: + case SafeChdirFailNotDir: + case SafeChdirFailChdirFailed: + error (0, errno, "%s", pathname); + state.exit_status = 1; + return; + + case SafeChdirFailSymlink: + error (0, 0, + _("warning: not following the symbolic link %s"), + pathname); + state.exit_status = 1; + return; + } } - for (namep = name_space; *namep; namep += file_len - pathname_len + 1) + for (idx=0; idx < dirinfo->size; ++idx) { + /* savedirinfo() may return dirinfo=NULL if extended information + * is not available. + */ + mode_t mode = (dirinfo->entries[idx].flags & SavedirHaveFileType) ? + dirinfo->entries[idx].type_info : 0; + namep = dirinfo->entries[idx].name; + /* Append this directory entry's name to the path being searched. */ file_len = pathname_len + strlen (namep); if (file_len > cur_path_size) @@ -478,62 +1954,125 @@ process_dir (pathname, name, pathlen, statp, parent) cur_name = cur_path + pathname_len - 1; strcpy (cur_name, namep); - curdepth++; - if (!no_leaf_check) - /* Normal case optimization. - On normal Unix filesystems, a directory that has no - subdirectories has two links: its name, and ".". Any - additional links are to the ".." entries of its - subdirectories. Once we have processed as many - subdirectories as there are additional links, we know - that the rest of the entries are non-directories -- - in other words, leaf files. */ - subdirs_left -= process_path (cur_path, cur_name, - subdirs_left == 0, pathname); - else - /* There might be weird (e.g., CD-ROM or MS-DOS) filesystems - mounted, which don't have Unix-like directory link counts. */ - process_path (cur_path, cur_name, false, pathname); - curdepth--; - } - - if (strcmp (name, ".")) - { - if (!dereference) + state.curdepth++; + if (!options.no_leaf_check && !subdirs_unreliable) { - if (chdir ("..") < 0) - /* We could go back and do the next command-line arg instead, - maybe using longjmp. */ - error (1, errno, "%s", parent); + if (mode && S_ISDIR(mode) && (subdirs_left == 0)) + { + /* This is a subdirectory, but the number of directories we + * have found now exceeds the number we would expect given + * the hard link count on the parent. This is likely to be + * a bug in the filesystem driver (e.g. Linux's + * /proc filesystem) or may just be a fact that the OS + * doesn't really handle hard links with Unix semantics. + * In the latter case, -noleaf should be used routinely. + */ + error(0, 0, _("WARNING: Hard link count is wrong for %s: this may be a bug in your filesystem driver. Automatically turning on find's -noleaf option. Earlier results may have failed to include directories that should have been searched."), + pathname); + state.exit_status = 1; /* We know the result is wrong, now */ + options.no_leaf_check = true; /* Don't make same + mistake again */ + subdirs_left = 1; /* band-aid for this iteration. */ + } + + /* Normal case optimization. On normal Unix + filesystems, a directory that has no subdirectories + has two links: its name, and ".". Any additional + links are to the ".." entries of its subdirectories. + Once we have processed as many subdirectories as + there are additional links, we know that the rest of + the entries are non-directories -- in other words, + leaf files. */ + subdirs_left -= process_path (cur_path, cur_name, + subdirs_left == 0, pathname, + mode); } else { -#ifndef HAVE_FCHDIR - if (chdir (starting_dir) || chdir (parent)) - error (1, errno, "%s", parent); -#else - if (fchdir (starting_desc) || chdir (parent)) - error (1, errno, "%s", parent); -#endif + /* There might be weird (e.g., CD-ROM or MS-DOS) filesystems + mounted, which don't have Unix-like directory link counts. */ + process_path (cur_path, cur_name, false, pathname, mode); + } + + state.curdepth--; + } + + + /* We're about to leave the directory. If there are any + * -execdir argument lists which have been built but have not + * yet been processed, do them now because they must be done in + * the same directory. + */ + complete_pending_execdirs(eval_tree); + + + if (strcmp (name, ".")) + { + enum SafeChdirStatus status; + struct dir_id did; + boolean did_stat = false; + + /* We could go back and do the next command-line arg + instead, maybe using longjmp. */ + char const *dir; + boolean deref = following_links() ? true : false; + + if ( (state.curdepth>0) && !deref) + dir = ".."; + else + { + chdir_back (); + dir = parent; + } + + status = safely_chdir (dir, TraversingUp, &stat_buf, SymlinkHandleDefault, &did_stat); + switch (status) + { + case SafeChdirOK: + break; + + case SafeChdirFailWouldBeUnableToReturn: + error (1, errno, "."); + return; + + case SafeChdirFailNonexistent: + case SafeChdirFailDestUnreadable: + case SafeChdirFailStat: + case SafeChdirFailSymlink: + case SafeChdirFailNotDir: + case SafeChdirFailChdirFailed: + error (1, errno, "%s", pathname); + return; + } + + if (dir_curr > 0) + { + did.dev = dir_ids[dir_curr-1].dev; + did.ino = dir_ids[dir_curr-1].ino; + } + else + { + did.dev = starting_stat_buf.st_dev; + did.ino = starting_stat_buf.st_ino; } } if (cur_path) free (cur_path); - free (name_space); + free_dirinfo(dirinfo); } } -/* Return true if there are no side effects in any of the predicates in - predicate list PRED, false if there are any. */ +/* Return true if there are no predicates with no_default_print in + predicate list PRED, false if there are any. + Returns true if default print should be performed */ static boolean -no_side_effects (pred) - struct predicate *pred; +default_prints (struct predicate *pred) { while (pred != NULL) { - if (pred->side_effects) + if (pred->no_default_print) return (false); pred = pred->pred_next; } diff --git a/src/bin/findutils/find/fstype.c b/src/bin/findutils/find/fstype.c index 56492a50c9..45c712ecca 100644 --- a/src/bin/findutils/find/fstype.c +++ b/src/bin/findutils/find/fstype.c @@ -1,10 +1,10 @@ /* fstype.c -- determine type of filesystems that files are on - Copyright (C) 1990, 91, 92, 93, 94 Free Software Foundation, Inc. + Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2004, 2005 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -12,144 +12,109 @@ GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ + +/* Written by David MacKenzie . + * + * Converted to use gnulib's read_file_system_list() + * by James Youngman (which saves a lot + * of manual hacking of configure.in). + */ -/* Written by David MacKenzie . */ #include -#include -#include -#include -#include "defs.h" -#include "modetype.h" #include +#include +#include + +#ifdef HAVE_SYS_TYPES_H +#include +#endif + +/* The presence of unistd.h is assumed by gnulib these days, so we + * might as well assume it too. + */ +#include + +#ifdef HAVE_SYS_MNTIO_H +#ifdef HAVE_FCNTL_H +#include +#endif +#include +#endif +#ifdef HAVE_SYS_MKDEV_H +#include +#endif + #ifdef STDC_HEADERS #include #else extern int errno; #endif -char *strdup (); -char *strstr (); +#include "defs.h" +#include "../gnulib/lib/dirname.h" +#include "xalloc.h" +#include "modetype.h" -static char *filesystem_type_uncached P_((char *path, char *relpath, struct stat *statp)); -static int xatoi P_((char *cp)); +/* Need declaration of function `xstrtoumax' */ +#include "../gnulib/lib/xstrtol.h" -#ifdef FSTYPE_MNTENT /* 4.3BSD, SunOS, HP-UX, Dynix, Irix. */ -#include -#if !defined(MOUNTED) -# if defined(MNT_MNTTAB) /* HP-UX. */ -# define MOUNTED MNT_MNTTAB -# endif -# if defined(MNTTABNAME) /* Dynix. */ -# define MOUNTED MNTTABNAME -# endif +#include "extendbuf.h" +#include "mountlist.h" + + + +#if ENABLE_NLS +# include +# define _(Text) gettext (Text) +#else +# define _(Text) Text #endif +#ifdef gettext_noop +# define N_(String) gettext_noop (String) +#else +/* See locate.c for explanation as to why not use (String) */ +# define N_(String) String #endif -#ifdef FSTYPE_GETMNT /* Ultrix. */ -#include -#include -#include +static char *filesystem_type_uncached PARAMS((const struct stat *statp, const char *path)); + + +/* Get MNTTYPE_IGNORE if it is available. */ +#if HAVE_MNTENT_H +# include +#endif +#if HAVE_SYS_MNTTAB_H +# include +# include #endif -#ifdef FSTYPE_USG_STATFS /* SVR3. */ -#include -#include -#endif -#ifdef FSTYPE_STATVFS /* SVR4. */ -#include -#include -#endif -#ifdef FSTYPE_STATFS /* 4.4BSD. */ -#include /* NetBSD needs this. */ -#include -#ifndef MFSNAMELEN /* NetBSD defines this. */ -static char * -fstype_to_string (t) - short t; + +static void +free_file_system_list(struct mount_entry *p) { -#ifdef INITMOUNTNAMES /* Defined in 4.4BSD, not in NET/2. */ - static char *mn[] = INITMOUNTNAMES; - if (t >= 0 && t <= MOUNT_MAXTYPE) - return mn[t]; - else - return "?"; -#else /* !INITMOUNTNAMES */ - switch (t) + while (p) { - case MOUNT_UFS: - return "ufs"; - case MOUNT_NFS: - return "nfs"; -#ifdef MOUNT_PC - case MOUNT_PC: - return "pc"; -#endif -#ifdef MOUNT_MFS - case MOUNT_MFS: - return "mfs"; -#endif -#ifdef MOUNT_LO - case MOUNT_LO: - return "lofs"; -#endif -#ifdef MOUNT_TFS - case MOUNT_TFS: - return "tfs"; -#endif -#ifdef MOUNT_TMP - case MOUNT_TMP: - return "tmp"; -#endif -#ifdef MOUNT_MSDOS - case MOUNT_MSDOS: - return "msdos"; -#endif -#ifdef MOUNT_ISO9660 - case MOUNT_ISO9660: - return "iso9660fs"; -#endif - default: - return "?"; - } -#endif /* !INITMOUNTNAMES */ -} -#endif /* !MFSNAMELEN */ -#endif /* FSTYPE_STATFS */ - -#ifdef FSTYPE_AIX_STATFS /* AIX. */ -#include -#include - -#define FSTYPE_STATFS /* Otherwise like 4.4BSD. */ -#define f_type f_vfstype - -static char * -fstype_to_string (t) - short t; -{ - switch (t) - { - case MNT_AIX: -#if 0 /* NFS filesystems are actually MNT_AIX. */ - return "aix"; -#endif - case MNT_NFS: - return "nfs"; - case MNT_JFS: - return "jfs"; - case MNT_CDROM: - return "cdrom"; - default: - return "?"; + struct mount_entry *pnext = p->me_next; + + free(p->me_devname); + free(p->me_mountdir); + + if(p->me_type_malloced) + free(p->me_type); + p->me_next = NULL; + free(p); + p = pnext; } } -#endif /* FSTYPE_AIX_STATFS */ + + + #ifdef AFS #include @@ -165,8 +130,7 @@ fstype_to_string (t) #endif static int -in_afs (path) - char *path; +in_afs (char *path) { static char space[2048]; struct ViceIoctl vi; @@ -191,10 +155,7 @@ static int fstype_known = 0; Return "unknown" if its filesystem type is unknown. */ char * -filesystem_type (path, relpath, statp) - char *path; - char *relpath; - struct stat *statp; +filesystem_type (const struct stat *statp, const char *path) { static char *current_fstype = NULL; static dev_t current_dev; @@ -206,181 +167,146 @@ filesystem_type (path, relpath, statp) free (current_fstype); } current_dev = statp->st_dev; - current_fstype = filesystem_type_uncached (path, relpath, statp); + current_fstype = filesystem_type_uncached (statp, path); return current_fstype; } +static int +set_fstype_devno(struct mount_entry *p) +{ + struct stat stbuf; + + if (p->me_dev == (dev_t)-1) + { + if (0 == (options.xstat)(p->me_mountdir, &stbuf)) + { + p->me_dev = stbuf.st_dev; + return 0; + } + else + { + return -1; + } + } + return 0; /* not needed */ +} + +static struct mount_entry * +must_read_fs_list(bool need_fs_type) +{ + struct mount_entry *entries = read_file_system_list(need_fs_type); + if (NULL == entries) + { + /* We cannot determine for sure which file we were trying to + * use because gnulib has extracted all that stuff away. + * Hence we cannot issue a specific error message here. + */ + error(1, 0, "Cannot read mounted filesystem list"); + } + return entries; +} + + + /* Return a newly allocated string naming the type of filesystem that the file PATH, described by STATP, is on. RELPATH is the file name relative to the current directory. Return "unknown" if its filesystem type is unknown. */ static char * -filesystem_type_uncached (path, relpath, statp) - char *path; - char *relpath; - struct stat *statp; +filesystem_type_uncached (const struct stat *statp, const char *path) { - char *type = NULL; - -#ifdef FSTYPE_MNTENT /* 4.3BSD, SunOS, HP-UX, Dynix, Irix. */ - char *table = MOUNTED; - FILE *mfp; - struct mntent *mnt; - - mfp = setmntent (table, "r"); - if (mfp == NULL) - error (1, errno, "%s", table); - - /* Find the entry with the same device number as STATP, and return - that entry's fstype. */ - while (type == NULL && (mnt = getmntent (mfp))) - { - char *devopt; - dev_t dev; - struct stat disk_stats; - -#ifdef MNTTYPE_IGNORE - if (!strcmp (mnt->mnt_type, MNTTYPE_IGNORE)) - continue; -#endif - - /* Newer systems like SunOS 4.1 keep the dev number in the mtab, - in the options string. For older systems, we need to stat the - directory that the filesystem is mounted on to get it. - - Unfortunately, the HPUX 9.x mnttab entries created by automountq - contain a dev= option but the option value does not match the - st_dev value of the file (maybe the lower 16 bits match?). */ - -#if !defined(hpux) && !defined(__hpux__) - devopt = strstr (mnt->mnt_opts, "dev="); - if (devopt) - { - if (devopt[4] == '0' && (devopt[5] == 'x' || devopt[5] == 'X')) - dev = xatoi (devopt + 6); - else - dev = xatoi (devopt + 4); - } - else -#endif /* not hpux */ - { - if (stat (mnt->mnt_dir, &disk_stats) == -1) - error (1, errno, "error in %s: %s", table, mnt->mnt_dir); - dev = disk_stats.st_dev; - } - - if (dev == statp->st_dev) - type = mnt->mnt_type; - } - - if (endmntent (mfp) == 0) - error (0, errno, "%s", table); -#endif - -#ifdef FSTYPE_GETMNT /* Ultrix. */ - int offset = 0; - struct fs_data fsd; - - while (type == NULL - && getmnt (&offset, &fsd, sizeof (fsd), NOSTAT_MANY, 0) > 0) - { - if (fsd.fd_req.dev == statp->st_dev) - type = gt_names[fsd.fd_req.fstype]; - } -#endif - -#ifdef FSTYPE_USG_STATFS /* SVR3. */ - struct statfs fss; - char typebuf[FSTYPSZ]; - - if (statfs (relpath, &fss, sizeof (struct statfs), 0) == -1) - { - /* Don't die if a file was just removed. */ - if (errno != ENOENT) - error (1, errno, "%s", path); - } - else if (!sysfs (GETFSTYP, fss.f_fstyp, typebuf)) - type = typebuf; -#endif - -#ifdef FSTYPE_STATVFS /* SVR4. */ - struct statvfs fss; - - if (statvfs (relpath, &fss) == -1) - { - /* Don't die if a file was just removed. */ - if (errno != ENOENT) - error (1, errno, "%s", path); - } - else - type = fss.f_basetype; -#endif - -#ifdef FSTYPE_STATFS /* 4.4BSD. */ - struct statfs fss; - char *p; - - if (S_ISLNK (statp->st_mode)) - p = dirname (relpath); - else - p = relpath; - - if (statfs (p, &fss) == -1) - { - /* Don't die if symlink to nonexisting file, or a file that was - just removed. */ - if (errno != ENOENT) - error (1, errno, "%s", path); - } - else - { -#ifdef MFSNAMELEN /* NetBSD. */ - type = xstrdup (fss.f_fstypename); -#else - type = fstype_to_string (fss.f_type); -#endif - } - if (p != relpath) - free (p); -#endif + struct mount_entry *entries, *entry; + char *type; #ifdef AFS - if ((!type || !strcmp (type, "xx")) && in_afs (relpath)) - type = "afs"; -#endif - - /* An unknown value can be caused by an ENOENT error condition. - Don't cache those values. */ - fstype_known = (type != NULL); - - return xstrdup (type ? type : "unknown"); -} - -#ifdef FSTYPE_MNTENT /* 4.3BSD etc. */ -/* Return the value of the hexadecimal number represented by CP. - No prefix (like '0x') or suffix (like 'h') is expected to be - part of CP. */ - -static int -xatoi (cp) - char *cp; -{ - int val; - - val = 0; - while (*cp) + if (in_afs(path)) { - if (*cp >= 'a' && *cp <= 'f') - val = val * 16 + *cp - 'a' + 10; - else if (*cp >= 'A' && *cp <= 'F') - val = val * 16 + *cp - 'A' + 10; - else if (*cp >= '0' && *cp <= '9') - val = val * 16 + *cp - '0'; - else - break; - cp++; + fstype_known = 1; + return xstrdup("afs"); } - return val; -} +#endif + + entries = must_read_fs_list(true); + for (type=NULL, entry=entries; entry; entry=entry->me_next) + { +#ifdef MNTTYPE_IGNORE + if (!strcmp (entry->me_type, MNTTYPE_IGNORE)) + continue; #endif + set_fstype_devno(entry); + if (entry->me_dev == statp->st_dev) + { + type = xstrdup(entry->me_type); + break; + } + } + free_file_system_list(entries); + + /* Don't cache unknown values. */ + fstype_known = (type != NULL); + + return type ? type : xstrdup(_("unknown")); +} + + +char * +get_mounted_filesystems (void) +{ + char *result = NULL; + size_t alloc_size = 0u; + size_t used = 0u; + struct mount_entry *entries, *entry; + + entries = must_read_fs_list(false); + for (entry=entries; entry; entry=entry->me_next) + { + size_t len; + +#ifdef MNTTYPE_IGNORE + if (!strcmp (entry->me_type, MNTTYPE_IGNORE)) + continue; +#endif + set_fstype_devno(entry); + + len = strlen(entry->me_mountdir) + 1; + result = extendbuf(result, used+len, &alloc_size); + strcpy(&result[used], entry->me_mountdir); + used += len; /* len already includes one for the \0 */ + } + + free_file_system_list(entries); + return result; +} + + +dev_t * +get_mounted_devices (size_t *n) +{ + size_t alloc_size = 0u; + size_t used = 0u; + struct mount_entry *entries, *entry; + dev_t *result = NULL; + + /* Use read_file_system_list() rather than must_read_fs_list() + * because on some system this is always called at startup, + * and find should only exit fatally if it needs to use the + * result of this operation. If we can't get the fs list + * but we never need the information, there is no need to fail. + */ + for (entry = entries = read_file_system_list(false); + entry; + entry = entry->me_next) + { + result = extendbuf(result, sizeof(dev_t)*(used+1), &alloc_size); + set_fstype_devno(entry); + result[used] = entry->me_dev; + ++used; + } + free_file_system_list(entries); + *n = used; + return result; +} + + + diff --git a/src/bin/findutils/find/parser.c b/src/bin/findutils/find/parser.c index 3bb87c89ce..cb88e88101 100644 --- a/src/bin/findutils/find/parser.c +++ b/src/bin/findutils/find/parser.c @@ -1,10 +1,11 @@ /* parser.c -- convert the command line args into an expression tree. - Copyright (C) 1990, 91, 92, 93, 94 Free Software Foundation, Inc. + Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, 2001, 2003, + 2004, 2005, 2007 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -12,19 +13,51 @@ GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ -#include -#include -#include + +#include "defs.h" #include -#include #include #include +#include #include "modechange.h" -#include "defs.h" #include "modetype.h" +#include "xstrtol.h" +#include "xalloc.h" +#include "quote.h" +#include "quotearg.h" +#include "buildcmd.h" +#include "nextelem.h" +#include "stdio-safer.h" +#include "regextype.h" +#include "gnulib-version.h" + +#ifdef HAVE_FCNTL_H +#include +#else +#include +#endif + +/* The presence of unistd.h is assumed by gnulib these days, so we + * might as well assume it too. + */ +/* We need for isatty(). */ +#include + +#if ENABLE_NLS +# include +# define _(Text) gettext (Text) +#else +# define _(Text) Text +#endif +#ifdef gettext_noop +# define N_(String) gettext_noop (String) +#else +/* See locate.c for explanation as to why not use (String) */ +# define N_(String) String +#endif #if !defined (isascii) || defined (STDC_HEADERS) #ifdef isascii @@ -33,223 +66,336 @@ #define isascii(c) 1 #endif -#define ISDIGIT(c) (isascii (c) && isdigit (c)) -#define ISUPPER(c) (isascii (c) && isupper (c)) +#define ISDIGIT(c) (isascii ((unsigned char)c) && isdigit ((unsigned char)c)) +#define ISUPPER(c) (isascii ((unsigned char)c) && isupper ((unsigned char)c)) -#ifndef _POSIX_VERSION -/* POSIX.1 header files should declare these. */ -struct group *getgrnam (); -struct passwd *getpwnam (); -#endif - -#ifdef CACHE_IDS -/* These two aren't specified by POSIX.1. */ -struct group *getgrent (); -struct passwd *getpwent (); -#endif - -#ifndef S_IFLNK -#define lstat stat -#endif - -char *strstr (); -int lstat (); -int stat (); -#ifndef atol /* for Linux */ -long atol (); -#endif -struct tm *localtime (); - -#ifdef _POSIX_SOURCE +#ifndef HAVE_ENDGRENT #define endgrent() +#endif +#ifndef HAVE_ENDPWENT #define endpwent() -#else -void endgrent (); -void endpwent (); #endif -static boolean parse_amin P_((char *argv[], int *arg_ptr)); -static boolean parse_and P_((char *argv[], int *arg_ptr)); -static boolean parse_anewer P_((char *argv[], int *arg_ptr)); -static boolean parse_atime P_((char *argv[], int *arg_ptr)); -boolean parse_close P_((char *argv[], int *arg_ptr)); -static boolean parse_cmin P_((char *argv[], int *arg_ptr)); -static boolean parse_cnewer P_((char *argv[], int *arg_ptr)); -static boolean parse_comma P_((char *argv[], int *arg_ptr)); -static boolean parse_ctime P_((char *argv[], int *arg_ptr)); -static boolean parse_daystart P_((char *argv[], int *arg_ptr)); -static boolean parse_depth P_((char *argv[], int *arg_ptr)); -static boolean parse_empty P_((char *argv[], int *arg_ptr)); -static boolean parse_exec P_((char *argv[], int *arg_ptr)); -static boolean parse_false P_((char *argv[], int *arg_ptr)); -static boolean parse_fls P_((char *argv[], int *arg_ptr)); -static boolean parse_fprintf P_((char *argv[], int *arg_ptr)); -static boolean parse_follow P_((char *argv[], int *arg_ptr)); -static boolean parse_fprint P_((char *argv[], int *arg_ptr)); -static boolean parse_fprint0 P_((char *argv[], int *arg_ptr)); -static boolean parse_fstype P_((char *argv[], int *arg_ptr)); -static boolean parse_gid P_((char *argv[], int *arg_ptr)); -static boolean parse_group P_((char *argv[], int *arg_ptr)); -static boolean parse_help P_((char *argv[], int *arg_ptr)); -static boolean parse_ilname P_((char *argv[], int *arg_ptr)); -static boolean parse_iname P_((char *argv[], int *arg_ptr)); -static boolean parse_inum P_((char *argv[], int *arg_ptr)); -static boolean parse_ipath P_((char *argv[], int *arg_ptr)); -static boolean parse_iregex P_((char *argv[], int *arg_ptr)); -static boolean parse_links P_((char *argv[], int *arg_ptr)); -static boolean parse_lname P_((char *argv[], int *arg_ptr)); -static boolean parse_ls P_((char *argv[], int *arg_ptr)); -static boolean parse_maxdepth P_((char *argv[], int *arg_ptr)); -static boolean parse_mindepth P_((char *argv[], int *arg_ptr)); -static boolean parse_mmin P_((char *argv[], int *arg_ptr)); -static boolean parse_mtime P_((char *argv[], int *arg_ptr)); -static boolean parse_name P_((char *argv[], int *arg_ptr)); -static boolean parse_negate P_((char *argv[], int *arg_ptr)); -static boolean parse_newer P_((char *argv[], int *arg_ptr)); -static boolean parse_noleaf P_((char *argv[], int *arg_ptr)); -static boolean parse_nogroup P_((char *argv[], int *arg_ptr)); -static boolean parse_nouser P_((char *argv[], int *arg_ptr)); -static boolean parse_ok P_((char *argv[], int *arg_ptr)); -boolean parse_open P_((char *argv[], int *arg_ptr)); -static boolean parse_or P_((char *argv[], int *arg_ptr)); -static boolean parse_path P_((char *argv[], int *arg_ptr)); -static boolean parse_perm P_((char *argv[], int *arg_ptr)); -boolean parse_print P_((char *argv[], int *arg_ptr)); -static boolean parse_print0 P_((char *argv[], int *arg_ptr)); -static boolean parse_printf P_((char *argv[], int *arg_ptr)); -static boolean parse_prune P_((char *argv[], int *arg_ptr)); -static boolean parse_regex P_((char *argv[], int *arg_ptr)); -static boolean insert_regex P_((char *argv[], int *arg_ptr, boolean ignore_case)); -static boolean parse_size P_((char *argv[], int *arg_ptr)); -static boolean parse_true P_((char *argv[], int *arg_ptr)); -static boolean parse_type P_((char *argv[], int *arg_ptr)); -static boolean parse_uid P_((char *argv[], int *arg_ptr)); -static boolean parse_used P_((char *argv[], int *arg_ptr)); -static boolean parse_user P_((char *argv[], int *arg_ptr)); -static boolean parse_version P_((char *argv[], int *arg_ptr)); -static boolean parse_xdev P_((char *argv[], int *arg_ptr)); -static boolean parse_xtype P_((char *argv[], int *arg_ptr)); +static boolean parse_amin PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_and PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_anewer PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_atime PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_cmin PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_cnewer PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_comma PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_ctime PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_daystart PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_delete PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_d PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_depth PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_empty PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_exec PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_execdir PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_false PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_fls PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_fprintf PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_follow PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_fprint PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_fprint0 PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_fstype PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_gid PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_group PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_help PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_ilname PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_iname PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_inum PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_ipath PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_iregex PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_iwholename PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_links PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_lname PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_ls PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_maxdepth PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_mindepth PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_mmin PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_mtime PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_name PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_negate PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_newer PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_noleaf PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_nogroup PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_nouser PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_nowarn PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_ok PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_okdir PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_or PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_path PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_perm PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_print0 PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_printf PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_prune PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_regex PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_regextype PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_samefile PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_size PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_true PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_type PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_uid PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_used PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_user PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_version PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_wholename PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_xdev PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_ignore_race PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_noignore_race PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_warn PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_xtype PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); +static boolean parse_quit PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); -static boolean insert_regex P_((char *argv[], int *arg_ptr, boolean ignore_case)); -static boolean insert_type P_((char *argv[], int *arg_ptr, boolean (*which_pred )())); -static boolean insert_fprintf P_((FILE *fp, boolean (*func )(), char *argv[], int *arg_ptr)); -static struct segment **make_segment P_((struct segment **segment, char *format, int len, int kind)); -static boolean insert_exec_ok P_((boolean (*func )(), char *argv[], int *arg_ptr)); -static boolean get_num_days P_((char *str, unsigned long *num_days, enum comparison_type *comp_type)); -static boolean insert_time P_((char *argv[], int *arg_ptr, PFB pred)); -static boolean get_num P_((char *str, unsigned long *num, enum comparison_type *comp_type)); -static boolean insert_num P_((char *argv[], int *arg_ptr, PFB pred)); -static FILE *open_output_file P_((char *path)); + + +boolean parse_print PARAMS((const struct parser_table*, char *argv[], int *arg_ptr)); + + + +static boolean insert_type PARAMS((char **argv, int *arg_ptr, const struct parser_table *entry, PRED_FUNC which_pred)); +static boolean insert_regex PARAMS((char *argv[], int *arg_ptr, const struct parser_table *entry, int regex_options)); +static boolean insert_fprintf PARAMS((FILE *fp, const struct parser_table *entry, PRED_FUNC func, char *argv[], int *arg_ptr)); + +static struct segment **make_segment PARAMS((struct segment **segment, char *format, int len, int kind)); +static boolean insert_exec_ok PARAMS((const char *action, const struct parser_table *entry, char *argv[], int *arg_ptr)); +static boolean get_num_days PARAMS((char *str, uintmax_t *num_days, enum comparison_type *comp_type)); +static boolean insert_time PARAMS((char **argv, int *arg_ptr, const struct parser_table* entry, PRED_FUNC pred)); +static boolean get_num PARAMS((char *str, uintmax_t *num, enum comparison_type *comp_type)); +static boolean insert_num PARAMS((char *argv[], int *arg_ptr, const struct parser_table *entry)); +static FILE *open_output_file PARAMS((char *path)); +static boolean stream_is_tty(FILE *fp); #ifdef DEBUG -char *find_pred_name(PFB pred_func); +char *find_pred_name PARAMS((PRED_FUNC pred_func)); #endif /* DEBUG */ -struct parser_table -{ - char *parser_name; - PFB parser_func; -}; + +#define PASTE(x,y) x##y +#define STRINGIFY(s) #s + +#define PARSE_OPTION(what,suffix) \ + { (ARG_OPTION), (what), PASTE(parse_,suffix), NULL } + +#define PARSE_POSOPT(what,suffix) \ + { (ARG_POSITIONAL_OPTION), (what), PASTE(parse_,suffix), NULL } + +#define PARSE_TEST(what,suffix) \ + { (ARG_TEST), (what), PASTE(parse_,suffix), PASTE(pred_,suffix) } + +#define PARSE_TEST_NP(what,suffix) \ + { (ARG_TEST), (what), PASTE(parse_,suffix), NULL } + +#define PARSE_ACTION(what,suffix) \ + { (ARG_ACTION), (what), PASTE(parse_,suffix), PASTE(pred_,suffix) } + +#define PARSE_ACTION_NP(what,suffix) \ + { (ARG_ACTION), (what), PASTE(parse_,suffix), NULL } + +#define PARSE_PUNCTUATION(what,suffix) \ + { (ARG_PUNCTUATION), (what), PASTE(parse_,suffix), PASTE(pred_,suffix) } + /* GNU find predicates that are not mentioned in POSIX.2 are marked `GNU'. If they are in some Unix versions of find, they are marked `Unix'. */ static struct parser_table const parse_table[] = { - {"!", parse_negate}, - {"not", parse_negate}, /* GNU */ - {"(", parse_open}, - {")", parse_close}, - {",", parse_comma}, /* GNU */ - {"a", parse_and}, - {"amin", parse_amin}, /* GNU */ - {"and", parse_and}, /* GNU */ - {"anewer", parse_anewer}, /* GNU */ - {"atime", parse_atime}, - {"cmin", parse_cmin}, /* GNU */ - {"cnewer", parse_cnewer}, /* GNU */ + PARSE_PUNCTUATION("!", negate), + PARSE_PUNCTUATION("not", negate), /* GNU */ + PARSE_PUNCTUATION("(", openparen), + PARSE_PUNCTUATION(")", closeparen), + PARSE_PUNCTUATION(",", comma), /* GNU */ + PARSE_PUNCTUATION("a", and), + PARSE_TEST ("amin", amin), /* GNU */ + PARSE_PUNCTUATION("and", and), /* GNU */ + PARSE_TEST ("anewer", anewer), /* GNU */ + PARSE_TEST ("atime", atime), + PARSE_TEST ("cmin", cmin), /* GNU */ + PARSE_TEST ("cnewer", cnewer), /* GNU */ + PARSE_TEST ("ctime", ctime), + PARSE_POSOPT ("daystart", daystart), /* GNU */ + PARSE_ACTION ("delete", delete), /* GNU, Mac OS, FreeBSD */ + PARSE_OPTION ("d", d), /* Mac OS X, FreeBSD, NetBSD, OpenBSD, but deprecated in favour of -depth */ + PARSE_OPTION ("depth", depth), + PARSE_TEST ("empty", empty), /* GNU */ + {ARG_ACTION, "exec", parse_exec, pred_exec}, /* POSIX */ + PARSE_ACTION ("execdir", execdir), /* *BSD, GNU */ + PARSE_ACTION ("fls", fls), /* GNU */ + PARSE_POSOPT ("follow", follow), /* GNU, Unix */ + PARSE_ACTION ("fprint", fprint), /* GNU */ + PARSE_ACTION ("fprint0", fprint0), /* GNU */ + {ARG_ACTION, "fprintf", parse_fprintf, pred_fprintf}, /* GNU */ + PARSE_TEST ("fstype", fstype), /* GNU, Unix */ + PARSE_TEST ("gid", gid), /* GNU */ + PARSE_TEST ("group", group), + PARSE_OPTION ("ignore_readdir_race", ignore_race), /* GNU */ + PARSE_TEST ("ilname", ilname), /* GNU */ + PARSE_TEST ("iname", iname), /* GNU */ + PARSE_TEST ("inum", inum), /* GNU, Unix */ + PARSE_TEST ("ipath", ipath), /* GNU, deprecated in favour of iwholename */ + PARSE_TEST_NP ("iregex", iregex), /* GNU */ + PARSE_TEST_NP ("iwholename", iwholename), /* GNU */ + PARSE_TEST ("links", links), + PARSE_TEST ("lname", lname), /* GNU */ + PARSE_ACTION ("ls", ls), /* GNU, Unix */ + PARSE_OPTION ("maxdepth", maxdepth), /* GNU */ + PARSE_OPTION ("mindepth", mindepth), /* GNU */ + PARSE_TEST ("mmin", mmin), /* GNU */ + PARSE_OPTION ("mount", xdev), /* Unix */ + PARSE_TEST ("mtime", mtime), + PARSE_TEST ("name", name), +#ifdef UNIMPLEMENTED_UNIX + PARSE(ARG_UNIMPLEMENTED, "ncpio", ncpio), /* Unix */ +#endif + PARSE_TEST ("newer", newer), + PARSE_OPTION ("noleaf", noleaf), /* GNU */ + PARSE_TEST ("nogroup", nogroup), + PARSE_TEST ("nouser", nouser), + PARSE_OPTION ("noignore_readdir_race", noignore_race), /* GNU */ + PARSE_OPTION ("nowarn", nowarn), /* GNU */ + PARSE_PUNCTUATION("o", or), + PARSE_PUNCTUATION("or", or), /* GNU */ + PARSE_ACTION ("ok", ok), + PARSE_ACTION ("okdir", okdir), /* GNU (-execdir is BSD) */ + PARSE_TEST ("path", path), /* GNU, HP-UX, GNU prefers wholename */ + PARSE_TEST ("perm", perm), + PARSE_ACTION ("print", print), + PARSE_ACTION ("print0", print0), /* GNU */ + {ARG_ACTION, "printf", parse_printf, NULL}, /* GNU */ + PARSE_ACTION ("prune", prune), + PARSE_ACTION ("quit", quit), /* GNU */ + PARSE_TEST ("regex", regex), /* GNU */ + PARSE_OPTION ("regextype", regextype), /* GNU */ + PARSE_TEST ("samefile", samefile), /* GNU */ + PARSE_TEST ("size", size), + PARSE_TEST ("type", type), + PARSE_TEST ("uid", uid), /* GNU */ + PARSE_TEST ("used", used), /* GNU */ + PARSE_TEST ("user", user), + PARSE_OPTION ("warn", warn), /* GNU */ + PARSE_TEST_NP ("wholename", wholename), /* GNU, replaces -path */ + PARSE_OPTION ("xdev", xdev), + PARSE_TEST ("xtype", xtype), /* GNU */ #ifdef UNIMPLEMENTED_UNIX /* It's pretty ugly for find to know about archive formats. Plus what it could do with cpio archives is very limited. Better to leave it out. */ - {"cpio", parse_cpio}, /* Unix */ + PARSE(ARG_UNIMPLEMENTED, "cpio", cpio), /* Unix */ #endif - {"ctime", parse_ctime}, - {"daystart", parse_daystart}, /* GNU */ - {"depth", parse_depth}, - {"empty", parse_empty}, /* GNU */ - {"exec", parse_exec}, - {"false", parse_false}, /* GNU */ - {"fls", parse_fls}, /* GNU */ - {"follow", parse_follow}, /* GNU, Unix */ - {"fprint", parse_fprint}, /* GNU */ - {"fprint0", parse_fprint0}, /* GNU */ - {"fprintf", parse_fprintf}, /* GNU */ - {"fstype", parse_fstype}, /* GNU, Unix */ - {"gid", parse_gid}, /* GNU */ - {"group", parse_group}, - {"help", parse_help}, /* GNU */ - {"-help", parse_help}, /* GNU */ - {"ilname", parse_ilname}, /* GNU */ - {"iname", parse_iname}, /* GNU */ - {"inum", parse_inum}, /* GNU, Unix */ - {"ipath", parse_ipath}, /* GNU */ - {"iregex", parse_iregex}, /* GNU */ - {"links", parse_links}, - {"lname", parse_lname}, /* GNU */ - {"ls", parse_ls}, /* GNU, Unix */ - {"maxdepth", parse_maxdepth}, /* GNU */ - {"mindepth", parse_mindepth}, /* GNU */ - {"mmin", parse_mmin}, /* GNU */ - {"mount", parse_xdev}, /* Unix */ - {"mtime", parse_mtime}, - {"name", parse_name}, -#ifdef UNIMPLEMENTED_UNIX - {"ncpio", parse_ncpio}, /* Unix */ -#endif - {"newer", parse_newer}, - {"noleaf", parse_noleaf}, /* GNU */ - {"nogroup", parse_nogroup}, - {"nouser", parse_nouser}, - {"o", parse_or}, - {"or", parse_or}, /* GNU */ - {"ok", parse_ok}, - {"path", parse_path}, /* GNU, HP-UX */ - {"perm", parse_perm}, - {"print", parse_print}, - {"print0", parse_print0}, /* GNU */ - {"printf", parse_printf}, /* GNU */ - {"prune", parse_prune}, - {"regex", parse_regex}, /* GNU */ - {"size", parse_size}, - {"true", parse_true}, /* GNU */ - {"type", parse_type}, - {"uid", parse_uid}, /* GNU */ - {"used", parse_used}, /* GNU */ - {"user", parse_user}, - {"version", parse_version}, /* GNU */ - {"-version", parse_version}, /* GNU */ - {"xdev", parse_xdev}, - {"xtype", parse_xtype}, /* GNU */ - {0, 0} + /* gnulib's stdbool.h might have made true and false into macros, + * so we can't leave named 'true' and 'false' tokens, so we have + * to expeant the relevant entries longhand. + */ + {ARG_TEST, "false", parse_false, pred_false}, /* GNU */ + {ARG_TEST, "true", parse_true, pred_true }, /* GNU */ + + /* Various other cases that don't fit neatly into our macro scheme. */ + {ARG_TEST, "help", parse_help, NULL}, /* GNU */ + {ARG_TEST, "-help", parse_help, NULL}, /* GNU */ + {ARG_TEST, "version", parse_version, NULL}, /* GNU */ + {ARG_TEST, "-version", parse_version, NULL}, /* GNU */ + {0, 0, 0, 0} }; + +static const char *first_nonoption_arg = NULL; + + + +void +parse_begin_user_args (char **args, int argno, const struct predicate *last, const struct predicate *predicates) +{ + (void) args; + (void) argno; + (void) last; + (void) predicates; + first_nonoption_arg = NULL; +} + +void +parse_end_user_args (char **args, int argno, const struct predicate *last, const struct predicate *predicates) +{ + /* does nothing */ + (void) args; + (void) argno; + (void) last; + (void) predicates; +} + + + + /* Return a pointer to the parser function to invoke for predicate SEARCH_NAME. Return NULL if SEARCH_NAME is not a valid predicate name. */ -PFB -find_parser (search_name) - char *search_name; +const struct parser_table* +find_parser (char *search_name) { int i; - + const char *original_arg = search_name; + if (*search_name == '-') search_name++; for (i = 0; parse_table[i].parser_name != 0; i++) - if (strcmp (parse_table[i].parser_name, search_name) == 0) - return (parse_table[i].parser_func); - return (NULL); + { + if (strcmp (parse_table[i].parser_name, search_name) == 0) + { + /* If this is an option, but we have already had a + * non-option argument, the user may be under the + * impression that the behaviour of the option + * argument is conditional on some preceding + * tests. This might typically be the case with, + * for example, -maxdepth. + * + * The options -daystart and -follow are exempt + * from this treatment, since their positioning + * in the command line does have an effect on + * subsequent tests but not previous ones. That + * might be intentional on the part of the user. + */ + if (parse_table[i].type != ARG_POSITIONAL_OPTION) + { + /* Something other than -follow/-daystart. + * If this is an option, check if it followed + * a non-option and if so, issue a warning. + */ + if (parse_table[i].type == ARG_OPTION) + { + if ((first_nonoption_arg != NULL) + && options.warnings ) + { + /* option which follows a non-option */ + error (0, 0, + _("warning: you have specified the %s " + "option after a non-option argument %s, " + "but options are not positional (%s affects " + "tests specified before it as well as those " + "specified after it). Please specify options " + "before other arguments.\n"), + original_arg, + first_nonoption_arg, + original_arg); + } + } + else + { + /* Not an option or a positional option, + * so remember we've seen it in order to + * use it in a possible future warning message. + */ + if (first_nonoption_arg == NULL) + { + first_nonoption_arg = original_arg; + } + } + } + + return &parse_table[i]; + } + } + return NULL; } /* The parsers are responsible to continue scanning ARGV for @@ -263,315 +409,342 @@ find_parser (search_name) The predicate structure is updated with the new information. */ static boolean -parse_amin (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_amin (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - unsigned long num; + uintmax_t num; enum comparison_type c_type; + time_t t; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; if (!get_num_days (argv[*arg_ptr], &num, &c_type)) - return (false); - our_pred = insert_primary (pred_amin); + return false; + t = options.cur_day_start + DAYSECS - num * 60; + our_pred = insert_primary (entry); our_pred->args.info.kind = c_type; - our_pred->args.info.l_val = cur_day_start + DAYSECS - num * 60; + our_pred->args.info.negative = t < 0; + our_pred->args.info.l_val = t; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_and (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_and (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - our_pred = get_new_pred (); + (void) argv; + (void) arg_ptr; + + our_pred = get_new_pred (entry); our_pred->pred_func = pred_and; #ifdef DEBUG our_pred->p_name = find_pred_name (pred_and); #endif /* DEBUG */ our_pred->p_type = BI_OP; our_pred->p_prec = AND_PREC; - our_pred->need_stat = false; - return (true); + our_pred->need_stat = our_pred->need_type = false; + return true; } static boolean -parse_anewer (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_anewer (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; struct stat stat_newer; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - if ((*xstat) (argv[*arg_ptr], &stat_newer)) + return false; + if ((*options.xstat) (argv[*arg_ptr], &stat_newer)) error (1, errno, "%s", argv[*arg_ptr]); - our_pred = insert_primary (pred_anewer); + our_pred = insert_primary (entry); our_pred->args.time = stat_newer.st_mtime; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_atime (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_atime (const struct parser_table* entry, char **argv, int *arg_ptr) { - return (insert_time (argv, arg_ptr, pred_atime)); + return insert_time (argv, arg_ptr, entry, pred_atime); } boolean -parse_close (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_closeparen (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - our_pred = get_new_pred (); - our_pred->pred_func = pred_close; + (void) argv; + (void) arg_ptr; + + our_pred = get_new_pred (entry); + our_pred->pred_func = pred_closeparen; #ifdef DEBUG - our_pred->p_name = find_pred_name (pred_close); + our_pred->p_name = find_pred_name (pred_closeparen); #endif /* DEBUG */ our_pred->p_type = CLOSE_PAREN; our_pred->p_prec = NO_PREC; - our_pred->need_stat = false; - return (true); + our_pred->need_stat = our_pred->need_type = false; + return true; } static boolean -parse_cmin (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_cmin (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - unsigned long num; + uintmax_t num; enum comparison_type c_type; + time_t t; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; if (!get_num_days (argv[*arg_ptr], &num, &c_type)) - return (false); - our_pred = insert_primary (pred_cmin); + return false; + t = options.cur_day_start + DAYSECS - num * 60; + our_pred = insert_primary (entry); our_pred->args.info.kind = c_type; - our_pred->args.info.l_val = cur_day_start + DAYSECS - num * 60; + our_pred->args.info.negative = t < 0; + our_pred->args.info.l_val = t; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_cnewer (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_cnewer (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; struct stat stat_newer; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - if ((*xstat) (argv[*arg_ptr], &stat_newer)) + return false; + if ((*options.xstat) (argv[*arg_ptr], &stat_newer)) error (1, errno, "%s", argv[*arg_ptr]); - our_pred = insert_primary (pred_cnewer); + our_pred = insert_primary (entry); our_pred->args.time = stat_newer.st_mtime; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_comma (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_comma (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - our_pred = get_new_pred (); + (void) argv; + (void) arg_ptr; + + our_pred = get_new_pred (entry); our_pred->pred_func = pred_comma; #ifdef DEBUG our_pred->p_name = find_pred_name (pred_comma); #endif /* DEBUG */ our_pred->p_type = BI_OP; our_pred->p_prec = COMMA_PREC; - our_pred->need_stat = false; - return (true); + our_pred->need_stat = our_pred->need_type = false; + return true; } static boolean -parse_ctime (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_ctime (const struct parser_table* entry, char **argv, int *arg_ptr) { - return (insert_time (argv, arg_ptr, pred_ctime)); + return insert_time (argv, arg_ptr, entry, pred_ctime); } static boolean -parse_daystart (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_daystart (const struct parser_table* entry, char **argv, int *arg_ptr) { struct tm *local; - if (full_days == false) + (void) entry; + (void) argv; + (void) arg_ptr; + + if (options.full_days == false) { - cur_day_start += DAYSECS; - local = localtime (&cur_day_start); - cur_day_start -= local->tm_sec + local->tm_min * 60 - + local->tm_hour * 3600; - full_days = true; + options.cur_day_start += DAYSECS; + local = localtime (&options.cur_day_start); + options.cur_day_start -= (local + ? (local->tm_sec + local->tm_min * 60 + + local->tm_hour * 3600) + : options.cur_day_start % DAYSECS); + options.full_days = true; } - return (true); + return true; } static boolean -parse_depth (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_delete (const struct parser_table* entry, char *argv[], int *arg_ptr) { - do_dir_first = false; - return (true); + struct predicate *our_pred; + (void) argv; + (void) arg_ptr; + + our_pred = insert_primary (entry); + our_pred->side_effects = our_pred->no_default_print = true; + /* -delete implies -depth */ + options.do_dir_first = false; + return true; +} + +static boolean +parse_depth (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + (void) entry; + (void) argv; + (void) arg_ptr; + + options.do_dir_first = false; + return true; } static boolean -parse_empty (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_d (const struct parser_table* entry, char **argv, int *arg_ptr) { - insert_primary (pred_empty); - return (true); + (void) argv; + (void) arg_ptr; + + if (options.warnings) + { + error (0, 0, + _("warning: the -d option is deprecated; please use -depth instead, because the latter is a POSIX-compliant feature.")); + } + return parse_depth(entry, argv, arg_ptr); +} + +static boolean +parse_empty (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + (void) argv; + (void) arg_ptr; + + insert_primary (entry); + return true; } static boolean -parse_exec (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_exec (const struct parser_table* entry, char **argv, int *arg_ptr) { - return (insert_exec_ok (pred_exec, argv, arg_ptr)); + return insert_exec_ok ("-exec", entry, argv, arg_ptr); } static boolean -parse_false (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_execdir (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + return insert_exec_ok ("-execdir", entry, argv, arg_ptr); +} + +static boolean +parse_false (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; + + (void) argv; + (void) arg_ptr; - our_pred = insert_primary (pred_false); - our_pred->need_stat = false; - return (true); + our_pred = insert_primary (entry); + our_pred->need_stat = our_pred->need_type = false; + our_pred->side_effects = our_pred->no_default_print = false; + return true; } static boolean -parse_fls (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_fls (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - our_pred = insert_primary (pred_fls); + return false; + our_pred = insert_primary (entry); our_pred->args.stream = open_output_file (argv[*arg_ptr]); - our_pred->side_effects = true; + our_pred->side_effects = our_pred->no_default_print = true; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_fprintf (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_fprintf (const struct parser_table* entry, char **argv, int *arg_ptr) { FILE *fp; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; if (argv[*arg_ptr + 1] == NULL) { /* Ensure we get "missing arg" message, not "invalid arg". */ (*arg_ptr)++; - return (false); + return false; } fp = open_output_file (argv[*arg_ptr]); (*arg_ptr)++; - return (insert_fprintf (fp, pred_fprintf, argv, arg_ptr)); + return insert_fprintf (fp, entry, pred_fprintf, argv, arg_ptr); } static boolean -parse_follow (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_follow (const struct parser_table* entry, char **argv, int *arg_ptr) { - dereference = true; - xstat = stat; - no_leaf_check = true; - return (true); + (void) entry; + (void) argv; + (void) arg_ptr; + + set_follow_state(SYMLINK_ALWAYS_DEREF); + return true; } static boolean -parse_fprint (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_fprint (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - our_pred = insert_primary (pred_fprint); - our_pred->args.stream = open_output_file (argv[*arg_ptr]); - our_pred->side_effects = true; - our_pred->need_stat = false; + return false; + our_pred = insert_primary (entry); + our_pred->args.printf_vec.segment = NULL; + our_pred->args.printf_vec.stream = open_output_file (argv[*arg_ptr]); + our_pred->args.printf_vec.dest_is_tty = stream_is_tty(our_pred->args.printf_vec.stream); + our_pred->args.printf_vec.quote_opts = clone_quoting_options (NULL); + our_pred->side_effects = our_pred->no_default_print = true; + our_pred->need_stat = our_pred->need_type = false; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_fprint0 (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_fprint0 (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - our_pred = insert_primary (pred_fprint0); + return false; + our_pred = insert_primary (entry); our_pred->args.stream = open_output_file (argv[*arg_ptr]); - our_pred->side_effects = true; - our_pred->need_stat = false; + our_pred->side_effects = our_pred->no_default_print = true; + our_pred->need_stat = our_pred->need_type = false; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_fstype (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_fstype (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - our_pred = insert_primary (pred_fstype); + return false; + our_pred = insert_primary (entry); our_pred->args.str = argv[*arg_ptr]; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_gid (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_gid (const struct parser_table* entry, char **argv, int *arg_ptr) { - return (insert_num (argv, arg_ptr, pred_gid)); + return insert_num (argv, arg_ptr, entry); } static boolean -parse_group (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_group (const struct parser_table* entry, char **argv, int *arg_ptr) { struct group *cur_gr; struct predicate *our_pred; @@ -579,7 +752,7 @@ parse_group (argv, arg_ptr) int gid_len; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; cur_gr = getgrnam (argv[*arg_ptr]); endgrent (); if (cur_gr != NULL) @@ -588,268 +761,335 @@ parse_group (argv, arg_ptr) { gid_len = strspn (argv[*arg_ptr], "0123456789"); if ((gid_len == 0) || (argv[*arg_ptr][gid_len] != '\0')) - return (false); + return false; gid = atoi (argv[*arg_ptr]); } - our_pred = insert_primary (pred_group); + our_pred = insert_primary (entry); our_pred->args.gid = gid; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_help (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_help (const struct parser_table* entry, char **argv, int *arg_ptr) { - printf ("\ -Usage: %s [path...] [expression]\n", program_name); - printf ("\ + (void) entry; + (void) argv; + (void) arg_ptr; + + printf (_("\ +Usage: %s [path...] [expression]\n"), program_name); + puts (_("\n\ default path is the current directory; default expression is -print\n\ -expression may consist of:\n\ +expression may consist of: operators, options, tests, and actions:\n")); + puts (_("\ operators (decreasing precedence; -and is implicit where no others are given):\n\ - ( EXPR ) ! EXPR -not EXPR EXPR1 -a EXPR2 EXPR1 -and EXPR2\n"); - printf ("\ - EXPR1 -o EXPR2 EXPR1 -or EXPR2 EXPR1 , EXPR2\n\ -options (always true): -daystart -depth -follow --help\n\ - -maxdepth LEVELS -mindepth LEVELS -mount -noleaf --version -xdev\n\ -tests (N can be +N or -N or N): -amin N -anewer FILE -atime N -cmin N\n"); - printf ("\ + ( EXPR ) ! EXPR -not EXPR EXPR1 -a EXPR2 EXPR1 -and EXPR2\n\ + EXPR1 -o EXPR2 EXPR1 -or EXPR2 EXPR1 , EXPR2\n")); + puts (_("\ +positional options (always true): -daystart -follow -regextype\n\n\ +normal options (always true, specified before other expressions):\n\ + -depth --help -maxdepth LEVELS -mindepth LEVELS -mount -noleaf\n\ + --version -xdev -ignore_readdir_race -noignore_readdir_race\n")); + puts (_("\ +tests (N can be +N or -N or N): -amin N -anewer FILE -atime N -cmin N\n\ -cnewer FILE -ctime N -empty -false -fstype TYPE -gid N -group NAME\n\ - -ilname PATTERN -iname PATTERN -inum N -ipath PATTERN -iregex PATTERN\n\ - -links N -lname PATTERN -mmin N -mtime N -name PATTERN -newer FILE\n"); - printf ("\ + -ilname PATTERN -iname PATTERN -inum N -iwholename PATTERN -iregex PATTERN\n\ + -links N -lname PATTERN -mmin N -mtime N -name PATTERN -newer FILE")); + puts (_("\ -nouser -nogroup -path PATTERN -perm [+-]MODE -regex PATTERN\n\ - -size N[bckw] -true -type [bcdpfls] -uid N -used N -user NAME\n\ - -xtype [bcdpfls]\n"); - printf ("\ -actions: -exec COMMAND ; -fprint FILE -fprint0 FILE -fprintf FILE FORMAT\n\ - -ok COMMAND ; -print -print0 -printf FORMAT -prune -ls\n"); + -wholename PATTERN -size N[bcwkMG] -true -type [bcdpflsD] -uid N\n\ + -used N -user NAME -xtype [bcdpfls]\n")); + puts (_("\ +actions: -delete -print0 -printf FORMAT -fprintf FILE FORMAT -print \n\ + -fprint0 FILE -fprint FILE -ls -fls FILE -prune -quit\n\ + -exec COMMAND ; -exec COMMAND {} + -ok COMMAND ;\n\ + -execdir COMMAND ; -execdir COMMAND {} + -okdir COMMAND ;\n\ +")); + puts (_("Report (and track progress on fixing) bugs via the findutils bug-reporting\n\ +page at http://savannah.gnu.org/ or, if you have no web access, by sending\n\ +email to .")); exit (0); } static boolean -parse_ilname (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_ilname (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - our_pred = insert_primary (pred_ilname); + return false; + our_pred = insert_primary (entry); our_pred->args.str = argv[*arg_ptr]; (*arg_ptr)++; - return (true); + return true; } + +/* sanity check the fnmatch() function to make sure + * it really is the GNU version. + */ +static boolean +fnmatch_sanitycheck(void) +{ + /* fprintf(stderr, "Performing find sanity check..."); */ + if (0 != fnmatch("foo", "foo", 0) + || 0 == fnmatch("Foo", "foo", 0) + || 0 != fnmatch("Foo", "foo", FNM_CASEFOLD)) + { + error (1, 0, _("sanity check of the fnmatch() library function failed.")); + /* fprintf(stderr, "FAILED\n"); */ + return false; + } + + /* fprintf(stderr, "OK\n"); */ + return true; +} + + static boolean -parse_iname (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +check_name_arg(const char *pred, const char *arg) +{ + if (options.warnings && strchr(arg, '/')) + { + error(0, 0,_("warning: Unix filenames usually don't contain slashes (though pathnames do). That means that '%s %s' will probably evaluate to false all the time on this system. You might find the '-wholename' test more useful, or perhaps '-samefile'. Alternatively, if you are using GNU grep, you could use 'find ... -print0 | grep -FzZ %s'."), + pred, arg, arg); + } + return true; /* allow it anyway */ +} + + + +static boolean +parse_iname (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - our_pred = insert_primary (pred_iname); - our_pred->need_stat = false; + return false; + if (!check_name_arg("-iname", argv[*arg_ptr])) + return false; + + fnmatch_sanitycheck(); + + our_pred = insert_primary (entry); + our_pred->need_stat = our_pred->need_type = false; our_pred->args.str = argv[*arg_ptr]; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_inum (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_inum (const struct parser_table* entry, char **argv, int *arg_ptr) { - return (insert_num (argv, arg_ptr, pred_inum)); + return insert_num (argv, arg_ptr, entry); +} + +/* -ipath is deprecated (at RMS's request) in favour of + * -iwholename. See the node "GNU Manuals" in standards.texi + * for the rationale for this (basically, GNU prefers the use + * of the phrase "file name" to "path name" + */ +static boolean +parse_ipath (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + error (0, 0, + _("warning: the predicate -ipath is deprecated; please use -iwholename instead.")); + + return parse_iwholename(entry, argv, arg_ptr); } static boolean -parse_ipath (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_iwholename (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - our_pred = insert_primary (pred_ipath); - our_pred->need_stat = false; + return false; + + fnmatch_sanitycheck(); + + our_pred = insert_primary_withpred (entry, pred_ipath); + our_pred->need_stat = our_pred->need_type = false; our_pred->args.str = argv[*arg_ptr]; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_iregex (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_iregex (const struct parser_table* entry, char **argv, int *arg_ptr) { - return insert_regex (argv, arg_ptr, true); + return insert_regex (argv, arg_ptr, entry, RE_ICASE|options.regex_options); } static boolean -parse_links (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_links (const struct parser_table* entry, char **argv, int *arg_ptr) { - return (insert_num (argv, arg_ptr, pred_links)); + return insert_num (argv, arg_ptr, entry); } static boolean -parse_lname (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_lname (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; + (void) argv; + (void) arg_ptr; + if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - our_pred = insert_primary (pred_lname); + return false; + + fnmatch_sanitycheck(); + + our_pred = insert_primary (entry); our_pred->args.str = argv[*arg_ptr]; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_ls (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_ls (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - our_pred = insert_primary (pred_ls); - our_pred->side_effects = true; - return (true); + (void) &argv; + (void) &arg_ptr; + + our_pred = insert_primary (entry); + our_pred->side_effects = our_pred->no_default_print = true; + return true; } static boolean -parse_maxdepth (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_maxdepth (const struct parser_table* entry, char **argv, int *arg_ptr) { int depth_len; + (void) entry; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; depth_len = strspn (argv[*arg_ptr], "0123456789"); if ((depth_len == 0) || (argv[*arg_ptr][depth_len] != '\0')) - return (false); - maxdepth = atoi (argv[*arg_ptr]); - if (maxdepth < 0) - return (false); + return false; + options.maxdepth = atoi (argv[*arg_ptr]); + if (options.maxdepth < 0) + return false; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_mindepth (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_mindepth (const struct parser_table* entry, char **argv, int *arg_ptr) { int depth_len; + (void) entry; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; depth_len = strspn (argv[*arg_ptr], "0123456789"); if ((depth_len == 0) || (argv[*arg_ptr][depth_len] != '\0')) - return (false); - mindepth = atoi (argv[*arg_ptr]); - if (mindepth < 0) - return (false); + return false; + options.mindepth = atoi (argv[*arg_ptr]); + if (options.mindepth < 0) + return false; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_mmin (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_mmin (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - unsigned long num; + uintmax_t num; enum comparison_type c_type; + time_t t; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; if (!get_num_days (argv[*arg_ptr], &num, &c_type)) - return (false); - our_pred = insert_primary (pred_mmin); + return false; + t = options.cur_day_start + DAYSECS - num * 60; + our_pred = insert_primary (entry); our_pred->args.info.kind = c_type; - our_pred->args.info.l_val = cur_day_start + DAYSECS - num * 60; + our_pred->args.info.negative = t < 0; + our_pred->args.info.l_val = t; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_mtime (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_mtime (const struct parser_table* entry, char **argv, int *arg_ptr) { - return (insert_time (argv, arg_ptr, pred_mtime)); + return insert_time (argv, arg_ptr, entry, pred_mtime); } static boolean -parse_name (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_name (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; + (void) argv; + (void) arg_ptr; + if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - our_pred = insert_primary (pred_name); - our_pred->need_stat = false; + return false; + if (!check_name_arg("-name", argv[*arg_ptr])) + return false; + fnmatch_sanitycheck(); + + our_pred = insert_primary (entry); + our_pred->need_stat = our_pred->need_type = false; our_pred->args.str = argv[*arg_ptr]; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_negate (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_negate (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - our_pred = get_new_pred_chk_op (); + (void) &argv; + (void) &arg_ptr; + + our_pred = get_new_pred_chk_op (entry); our_pred->pred_func = pred_negate; #ifdef DEBUG our_pred->p_name = find_pred_name (pred_negate); #endif /* DEBUG */ our_pred->p_type = UNI_OP; our_pred->p_prec = NEGATE_PREC; - our_pred->need_stat = false; - return (true); + our_pred->need_stat = our_pred->need_type = false; + return true; } static boolean -parse_newer (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_newer (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; struct stat stat_newer; + (void) argv; + (void) arg_ptr; + if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - if ((*xstat) (argv[*arg_ptr], &stat_newer)) + return false; + if ((*options.xstat) (argv[*arg_ptr], &stat_newer)) error (1, errno, "%s", argv[*arg_ptr]); - our_pred = insert_primary (pred_newer); + our_pred = insert_primary (entry); our_pred->args.time = stat_newer.st_mtime; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_noleaf (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_noleaf (const struct parser_table* entry, char **argv, int *arg_ptr) { - no_leaf_check = true; + (void) &argv; + (void) &arg_ptr; + (void) entry; + + options.no_leaf_check = true; return true; } @@ -870,13 +1110,14 @@ unsigned gid_allocated; #endif static boolean -parse_nogroup (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_nogroup (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - our_pred = insert_primary (pred_nogroup); + (void) &argv; + (void) &arg_ptr; + + our_pred = insert_primary (entry); #ifdef CACHE_IDS if (gid_unused == NULL) { @@ -901,17 +1142,18 @@ parse_nogroup (argv, arg_ptr) endgrent (); } #endif - return (true); + return true; } static boolean -parse_nouser (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_nouser (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; + (void) argv; + (void) arg_ptr; + - our_pred = insert_primary (pred_nouser); + our_pred = insert_primary (entry); #ifdef CACHE_IDS if (uid_unused == NULL) { @@ -936,198 +1178,319 @@ parse_nouser (argv, arg_ptr) endpwent (); } #endif - return (true); + return true; } static boolean -parse_ok (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_nowarn (const struct parser_table* entry, char **argv, int *arg_ptr) { - return (insert_exec_ok (pred_ok, argv, arg_ptr)); + (void) argv; + (void) arg_ptr; + (void) entry; + + options.warnings = false; + return true;; +} + +static boolean +parse_ok (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + return insert_exec_ok ("-ok", entry, argv, arg_ptr); +} + +static boolean +parse_okdir (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + return insert_exec_ok ("-okdir", entry, argv, arg_ptr); } boolean -parse_open (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_openparen (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - our_pred = get_new_pred_chk_op (); - our_pred->pred_func = pred_open; + (void) argv; + (void) arg_ptr; + + our_pred = get_new_pred_chk_op (entry); + our_pred->pred_func = pred_openparen; #ifdef DEBUG - our_pred->p_name = find_pred_name (pred_open); + our_pred->p_name = find_pred_name (pred_openparen); #endif /* DEBUG */ our_pred->p_type = OPEN_PAREN; our_pred->p_prec = NO_PREC; - our_pred->need_stat = false; - return (true); + our_pred->need_stat = our_pred->need_type = false; + return true; } static boolean -parse_or (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_or (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - our_pred = get_new_pred (); + (void) argv; + (void) arg_ptr; + + our_pred = get_new_pred (entry); our_pred->pred_func = pred_or; #ifdef DEBUG our_pred->p_name = find_pred_name (pred_or); #endif /* DEBUG */ our_pred->p_type = BI_OP; our_pred->p_prec = OR_PREC; - our_pred->need_stat = false; - return (true); + our_pred->need_stat = our_pred->need_type = false; + return true; +} + +/* -path is deprecated (at RMS's request) in favour of + * -iwholename. See the node "GNU Manuals" in standards.texi + * for the rationale for this (basically, GNU prefers the use + * of the phrase "file name" to "path name". + * + * We do not issue a warning that this usage is deprecated + * since HPUX find supports this predicate also. + */ +static boolean +parse_path (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + return parse_wholename(entry, argv, arg_ptr); } static boolean -parse_path (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_wholename (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - our_pred = insert_primary (pred_path); - our_pred->need_stat = false; + return false; + our_pred = insert_primary_withpred (entry, pred_path); + our_pred->need_stat = our_pred->need_type = false; our_pred->args.str = argv[*arg_ptr]; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_perm (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_perm (const struct parser_table* entry, char **argv, int *arg_ptr) { - unsigned long perm_val; + mode_t perm_val[2]; int mode_start = 0; - struct mode_change *change; + boolean havekind = false; + enum permissions_type kind = PERM_EXACT; + struct mode_change *change = NULL; struct predicate *our_pred; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; switch (argv[*arg_ptr][0]) { case '-': - case '+': mode_start = 1; + kind = PERM_AT_LEAST; + havekind = true; break; + + case '+': + change = mode_compile (argv[*arg_ptr]); + if (NULL == change) + { + /* Most likely the caller is an old script that is still + * using the obsolete GNU syntax '-perm +MODE'. This old + * syntax was withdrawn in favor of '-perm /MODE' because + * it is incompatible with POSIX in some cases, but we + * still support uses of it that are not incompatible with + * POSIX. + */ + mode_start = 1; + kind = PERM_ANY; + } + else + { + /* This is a POSIX-compatible usage */ + mode_start = 0; + kind = PERM_EXACT; + } + havekind = true; + break; + + case '/': /* GNU extension */ + mode_start = 1; + kind = PERM_ANY; + havekind = true; + break; + default: - /* empty */ + /* For example, '-perm 0644', which is valid and matches + * only files whose mode is exactly 0644. + * + * We do nothing here, because mode_start and kind are already + * correctly set. + */ break; } - change = mode_compile (argv[*arg_ptr] + mode_start, MODE_MASK_PLUS); - if (change == MODE_INVALID) - error (1, 0, "invalid mode `%s'", argv[*arg_ptr]); - else if (change == MODE_MEMORY_EXHAUSTED) - error (1, 0, "virtual memory exhausted"); - perm_val = mode_adjust (0, change); - mode_free (change); - - our_pred = insert_primary (pred_perm); - - switch (argv[*arg_ptr][0]) + if (NULL == change) { - case '-': - /* Set magic flag to indicate true if at least the given bits are set. */ - our_pred->args.perm = (perm_val & 07777) | 010000; - break; - case '+': - /* Set magic flag to indicate true if any of the given bits are set. */ - our_pred->args.perm = (perm_val & 07777) | 020000; - break; - default: - /* True if exactly the given bits are set. */ - our_pred->args.perm = (perm_val & 07777); - break; + change = mode_compile (argv[*arg_ptr] + mode_start); + if (NULL == change) + error (1, 0, _("invalid mode `%s'"), argv[*arg_ptr]); } + perm_val[0] = mode_adjust (0, false, 0, change, NULL); + perm_val[1] = mode_adjust (0, true, 0, change, NULL); + free (change); + + our_pred = insert_primary (entry); + + if (havekind) + { + our_pred->args.perm.kind = kind; + } + else + { + + switch (argv[*arg_ptr][0]) + { + case '-': + our_pred->args.perm.kind = PERM_AT_LEAST; + break; + case '+': + our_pred->args.perm.kind = PERM_ANY; + break; + default: + our_pred->args.perm.kind = PERM_EXACT; + break; + } + } + + if (('/' == argv[*arg_ptr][0]) && (0 == perm_val[0]) && (0 == perm_val[1])) + { + /* The meaning of -perm /000 will change in the future. + * It currently matches no files, but like -perm -000 it + * should match all files. + */ + error (0, 0, + _("warning: you have specified a mode pattern %s which is " + "equivalent to 000. The meaning of -perm /000 will soon be " + "changed to be consistent with -perm -000; that is, at the " + "moment it matches no files but it will soon be changed to " + "match all files."), + argv[*arg_ptr]); + } + + memcpy (our_pred->args.perm.val, perm_val, sizeof perm_val); (*arg_ptr)++; - return (true); + return true; } boolean -parse_print (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_print (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - our_pred = insert_primary (pred_print); + (void) argv; + (void) arg_ptr; + + our_pred = insert_primary (entry); /* -print has the side effect of printing. This prevents us from doing undesired multiple printing when the user has already specified -print. */ - our_pred->side_effects = true; - our_pred->need_stat = false; - return (true); + our_pred->side_effects = our_pred->no_default_print = true; + our_pred->need_stat = our_pred->need_type = false; + our_pred->args.printf_vec.segment = NULL; + our_pred->args.printf_vec.stream = stdout; + our_pred->args.printf_vec.dest_is_tty = stream_is_tty(stdout); + our_pred->args.printf_vec.quote_opts = clone_quoting_options (NULL); + + return true; } static boolean -parse_print0 (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_print0 (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - our_pred = insert_primary (pred_print0); + (void) argv; + (void) arg_ptr; + + our_pred = insert_primary (entry); /* -print0 has the side effect of printing. This prevents us from doing undesired multiple printing when the user has already specified -print0. */ - our_pred->side_effects = true; - our_pred->need_stat = false; - return (true); + our_pred->side_effects = our_pred->no_default_print = true; + our_pred->need_stat = our_pred->need_type = false; + return true; } static boolean -parse_printf (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_printf (const struct parser_table* entry, char **argv, int *arg_ptr) { if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - return (insert_fprintf (stdout, pred_fprintf, argv, arg_ptr)); + return false; + return insert_fprintf (stdout, entry, pred_fprintf, argv, arg_ptr); } static boolean -parse_prune (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_prune (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - our_pred = insert_primary (pred_prune); - our_pred->need_stat = false; - return (true); + (void) argv; + (void) arg_ptr; + + our_pred = insert_primary (entry); + our_pred->need_stat = our_pred->need_type = false; + /* -prune has a side effect that it does not descend into + the current directory. */ + our_pred->side_effects = true; + our_pred->no_default_print = false; + return true; } -static boolean -parse_regex (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +static boolean +parse_quit (const struct parser_table* entry, char **argv, int *arg_ptr) { - return insert_regex (argv, arg_ptr, false); + struct predicate *our_pred = insert_primary (entry); + (void) argv; + (void) arg_ptr; + our_pred->need_stat = our_pred->need_type = false; + our_pred->side_effects = true; /* Exiting is a side effect... */ + our_pred->no_default_print = false; /* Don't inhibit the default print, though. */ + return true; +} + + +static boolean +parse_regextype (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + if ((argv == NULL) || (argv[*arg_ptr] == NULL)) + return false; + + /* collect the regex type name */ + options.regex_options = get_regex_type(argv[*arg_ptr]); + (*arg_ptr)++; + + return true; +} + + +static boolean +parse_regex (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + return insert_regex (argv, arg_ptr, entry, options.regex_options); } static boolean -insert_regex (argv, arg_ptr, ignore_case) - char *argv[]; - int *arg_ptr; - boolean ignore_case; +insert_regex (char **argv, int *arg_ptr, const struct parser_table *entry, int regex_options) { struct predicate *our_pred; struct re_pattern_buffer *re; const char *error_message; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); - our_pred = insert_primary (pred_regex); - our_pred->need_stat = false; + return false; + our_pred = insert_primary_withpred (entry, pred_regex); + our_pred->need_stat = our_pred->need_type = false; re = (struct re_pattern_buffer *) xmalloc (sizeof (struct re_pattern_buffer)); our_pred->args.regex = re; @@ -1135,42 +1498,32 @@ insert_regex (argv, arg_ptr, ignore_case) re->buffer = (unsigned char *) xmalloc (re->allocated); re->fastmap = NULL; - if (ignore_case) - { - unsigned i; - - re->translate = xmalloc (256); - /* Map uppercase characters to corresponding lowercase ones. */ - for (i = 0; i < 256; i++) - re->translate[i] = ISUPPER (i) ? tolower (i) : i; - } - else - re->translate = NULL; - + re_set_syntax(regex_options); + re->syntax = regex_options; + re->translate = NULL; + error_message = re_compile_pattern (argv[*arg_ptr], strlen (argv[*arg_ptr]), re); if (error_message) error (1, 0, "%s", error_message); (*arg_ptr)++; - return (true); + return true; } static boolean -parse_size (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_size (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - unsigned long num; + uintmax_t num; enum comparison_type c_type; int blksize = 512; int len; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; len = strlen (argv[*arg_ptr]); if (len == 0) - error (1, 0, "invalid null argument to -size"); + error (1, 0, _("invalid null argument to -size")); switch (argv[*arg_ptr][len - 1]) { case 'b': @@ -1188,6 +1541,16 @@ parse_size (argv, arg_ptr) argv[*arg_ptr][len - 1] = '\0'; break; + case 'M': /* Megabytes */ + blksize = 1024*1024; + argv[*arg_ptr][len - 1] = '\0'; + break; + + case 'G': /* Gigabytes */ + blksize = 1024*1024*1024; + argv[*arg_ptr][len - 1] = '\0'; + break; + case 'w': blksize = 2; argv[*arg_ptr][len - 1] = '\0'; @@ -1206,71 +1569,88 @@ parse_size (argv, arg_ptr) break; default: - error (1, 0, "invalid -size type `%c'", argv[*arg_ptr][len - 1]); + error (1, 0, _("invalid -size type `%c'"), argv[*arg_ptr][len - 1]); } if (!get_num (argv[*arg_ptr], &num, &c_type)) - return (false); - our_pred = insert_primary (pred_size); + return false; + our_pred = insert_primary (entry); our_pred->args.size.kind = c_type; our_pred->args.size.blocksize = blksize; our_pred->args.size.size = num; (*arg_ptr)++; - return (true); + return true; } + static boolean -parse_true (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_samefile (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + struct predicate *our_pred; + struct stat st; + + if ((argv == NULL) || (argv[*arg_ptr] == NULL)) + return false; + if ((*options.xstat) (argv[*arg_ptr], &st)) + error (1, errno, "%s", argv[*arg_ptr]); + + our_pred = insert_primary (entry); + our_pred->args.fileid.ino = st.st_ino; + our_pred->args.fileid.dev = st.st_dev; + our_pred->need_type = false; + our_pred->need_stat = true; + (*arg_ptr)++; + return true; +} + + +static boolean +parse_true (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - our_pred = insert_primary (pred_true); - our_pred->need_stat = false; - return (true); + (void) argv; + (void) arg_ptr; + + our_pred = insert_primary (entry); + our_pred->need_stat = our_pred->need_type = false; + return true; } static boolean -parse_type (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_type (const struct parser_table* entry, char **argv, int *arg_ptr) { - return insert_type (argv, arg_ptr, pred_type); + return insert_type (argv, arg_ptr, entry, pred_type); } static boolean -parse_uid (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_uid (const struct parser_table* entry, char **argv, int *arg_ptr) { - return (insert_num (argv, arg_ptr, pred_uid)); + return insert_num (argv, arg_ptr, entry); } static boolean -parse_used (argv, arg_ptr) - char *argv[]; - int *arg_ptr; - +parse_used (const struct parser_table* entry, char **argv, int *arg_ptr) { struct predicate *our_pred; - unsigned long num_days; + uintmax_t num_days; enum comparison_type c_type; + time_t t; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; if (!get_num (argv[*arg_ptr], &num_days, &c_type)) - return (false); - our_pred = insert_primary (pred_used); + return false; + t = num_days * DAYSECS; + our_pred = insert_primary (entry); our_pred->args.info.kind = c_type; - our_pred->args.info.l_val = num_days * DAYSECS; + our_pred->args.info.negative = t < 0; + our_pred->args.info.l_val = t; (*arg_ptr)++; - return (true); + return true; } static boolean -parse_user (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_user (const struct parser_table* entry, char **argv, int *arg_ptr) { struct passwd *cur_pwd; struct predicate *our_pred; @@ -1278,7 +1658,7 @@ parse_user (argv, arg_ptr) int uid_len; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; cur_pwd = getpwnam (argv[*arg_ptr]); endpwent (); if (cur_pwd != NULL) @@ -1287,56 +1667,123 @@ parse_user (argv, arg_ptr) { uid_len = strspn (argv[*arg_ptr], "0123456789"); if ((uid_len == 0) || (argv[*arg_ptr][uid_len] != '\0')) - return (false); + return false; uid = atoi (argv[*arg_ptr]); } - our_pred = insert_primary (pred_user); + our_pred = insert_primary (entry); our_pred->args.uid = uid; (*arg_ptr)++; - return (true); -} - -static boolean -parse_version (argv, arg_ptr) - char *argv[]; - int *arg_ptr; -{ - extern char *version_string; - - fflush (stderr); - printf ("GNU find version %s\n", version_string); - exit (0); -} - -static boolean -parse_xdev (argv, arg_ptr) - char *argv[]; - int *arg_ptr; -{ - stay_on_filesystem = true; return true; } static boolean -parse_xtype (argv, arg_ptr) - char *argv[]; - int *arg_ptr; +parse_version (const struct parser_table* entry, char **argv, int *arg_ptr) { - return insert_type (argv, arg_ptr, pred_xtype); + extern char *version_string; + int features = 0; + + (void) argv; + (void) arg_ptr; + (void) entry; + + fflush (stderr); + printf (_("GNU find version %s\n"), version_string); + printf (_("Built using GNU gnulib version %s\n"), gnulib_version); + printf (_("Features enabled: ")); + +#if CACHE_IDS + printf("CACHE_IDS "); + ++features; +#endif +#if DEBUG + printf("DEBUG "); + ++features; +#endif +#if DEBUG_STAT + printf("DEBUG_STAT "); + ++features; +#endif +#if defined(USE_STRUCT_DIRENT_D_TYPE) && defined(HAVE_STRUCT_DIRENT_D_TYPE) + printf("D_TYPE "); + ++features; +#endif +#if defined(O_NOFOLLOW) + printf("O_NOFOLLOW(%s) ", + (options.open_nofollow_available ? "enabled" : "disabled")); + ++features; +#endif +#if defined(LEAF_OPTIMISATION) + printf("LEAF_OPTIMISATION "); + ++features; +#endif + if (0 == features) + { + /* For the moment, leave this as English in case someone wants + to parse these strings. */ + printf("none"); + } + printf("\n"); + + exit (0); +} + +static boolean +parse_xdev (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + (void) argv; + (void) arg_ptr; + (void) entry; + options.stay_on_filesystem = true; + return true; +} + +static boolean +parse_ignore_race (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + (void) argv; + (void) arg_ptr; + (void) entry; + options.ignore_readdir_race = true; + return true; +} + +static boolean +parse_noignore_race (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + (void) argv; + (void) arg_ptr; + (void) entry; + options.ignore_readdir_race = false; + return true; +} + +static boolean +parse_warn (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + (void) argv; + (void) arg_ptr; + (void) entry; + options.warnings = true; + return true; +} + +static boolean +parse_xtype (const struct parser_table* entry, char **argv, int *arg_ptr) +{ + (void) argv; + (void) arg_ptr; + return insert_type (argv, arg_ptr, entry, pred_xtype); } static boolean -insert_type (argv, arg_ptr, which_pred) - char *argv[]; - int *arg_ptr; - boolean (*which_pred) (); +insert_type (char **argv, int *arg_ptr, const struct parser_table *entry, PRED_FUNC which_pred) { - unsigned long type_cell; + mode_t type_cell; struct predicate *our_pred; if ((argv == NULL) || (argv[*arg_ptr] == NULL) || (strlen (argv[*arg_ptr]) != 1)) - return (false); + return false; switch (argv[*arg_ptr][0]) { case 'b': /* block special */ @@ -1365,26 +1812,63 @@ insert_type (argv, arg_ptr, which_pred) case 's': /* socket */ type_cell = S_IFSOCK; break; +#endif +#ifdef S_IFDOOR + case 'D': /* Solaris door */ + type_cell = S_IFDOOR; + break; #endif default: /* None of the above ... nuke 'em. */ - return (false); + return false; + } + our_pred = insert_primary_withpred (entry, which_pred); + + /* Figure out if we will need to stat the file, because if we don't + * need to follow symlinks, we can avoid a stat call by using + * struct dirent.d_type. + */ + if (which_pred == pred_xtype) + { + our_pred->need_stat = true; + our_pred->need_type = false; + } + else + { + our_pred->need_stat = false; /* struct dirent is enough */ + our_pred->need_type = true; } - our_pred = insert_primary (which_pred); our_pred->args.type = type_cell; (*arg_ptr)++; /* Move on to next argument. */ - return (true); + return true; } + +/* Return true if the file accessed via FP is a terminal. + */ +static boolean +stream_is_tty(FILE *fp) +{ + int fd = fileno(fp); + if (-1 == fd) + { + return false; /* not a valid stream */ + } + else + { + return isatty(fd) ? true : false; + } + +} + + + /* If true, we've determined that the current fprintf predicate uses stat information. */ static boolean fprintf_stat_needed; +/* XXX: do we need to pass FUNC to this function? */ static boolean -insert_fprintf (fp, func, argv, arg_ptr) - FILE *fp; - boolean (*func) (); - char *argv[]; - int *arg_ptr; +insert_fprintf (FILE *fp, const struct parser_table *entry, PRED_FUNC func, char **argv, int *arg_ptr) { char *format; /* Beginning of unprocessed format string. */ register char *scan; /* Current address in scanning `format'. */ @@ -1395,9 +1879,11 @@ insert_fprintf (fp, func, argv, arg_ptr) format = argv[(*arg_ptr)++]; fprintf_stat_needed = false; /* Might be overridden later. */ - our_pred = insert_primary (func); - our_pred->side_effects = true; + our_pred = insert_primary_withpred (entry, func); + our_pred->side_effects = our_pred->no_default_print = true; our_pred->args.printf_vec.stream = fp; + our_pred->args.printf_vec.dest_is_tty = stream_is_tty(fp); + our_pred->args.printf_vec.quote_opts = clone_quoting_options (NULL); segmentp = &our_pred->args.printf_vec.segment; *segmentp = NULL; @@ -1429,7 +1915,7 @@ insert_fprintf (fp, func, argv, arg_ptr) case 'c': make_segment (segmentp, format, scan - format, KIND_STOP); our_pred->need_stat = fprintf_stat_needed; - return (true); + return true; case 'f': *scan = '\f'; break; @@ -1449,7 +1935,8 @@ insert_fprintf (fp, func, argv, arg_ptr) /* *scan = '\\'; * it already is */ break; default: - error (0, 0, "warning: unrecognized escape `\\%c'", *scan2); + error (0, 0, + _("warning: unrecognized escape `\\%c'"), *scan2); scan++; continue; } @@ -1461,7 +1948,12 @@ insert_fprintf (fp, func, argv, arg_ptr) } else if (*scan == '%') { - if (scan[1] == '%') + if (scan[1] == 0) + { + /* Trailing %. We don't like those. */ + error (1, 0, _("error: %s at end of format string"), scan); + } + else if (scan[1] == '%') { segmentp = make_segment (segmentp, format, scan - format + 1, KIND_PLAIN); @@ -1477,7 +1969,7 @@ insert_fprintf (fp, func, argv, arg_ptr) if (*scan2 == '.') for (scan2++; ISDIGIT (*scan2); scan2++) /* Do nothing. */ ; - if (strchr ("abcdfFgGhHiklmnpPstuU", *scan2)) + if (strchr ("abcdDfFgGhHiklmMnpPstuUyY", *scan2)) { segmentp = make_segment (segmentp, format, scan2 - format, (int) *scan2); @@ -1495,7 +1987,7 @@ insert_fprintf (fp, func, argv, arg_ptr) else { /* An unrecognized % escape. Print the char after the %. */ - error (0, 0, "warning: unrecognized format directive `%%%c'", + error (0, 0, _("warning: unrecognized format directive `%%%c'"), *scan2); segmentp = make_segment (segmentp, format, scan - format, KIND_PLAIN); @@ -1507,8 +1999,9 @@ insert_fprintf (fp, func, argv, arg_ptr) if (scan > format) make_segment (segmentp, format, scan - format, KIND_PLAIN); + our_pred->need_type = false; our_pred->need_stat = fprintf_stat_needed; - return (true); + return true; } /* Create a new fprintf segment in *SEGMENT, with type KIND, @@ -1516,10 +2009,7 @@ insert_fprintf (fp, func, argv, arg_ptr) Return the address of the `next' pointer of the new segment. */ static struct segment ** -make_segment (segment, format, len, kind) - struct segment **segment; - char *format; - int len, kind; +make_segment (struct segment **segment, char *format, int len, int kind) { char *fmt; @@ -1529,7 +2019,7 @@ make_segment (segment, format, len, kind) (*segment)->next = NULL; (*segment)->text_len = len; - fmt = (*segment)->text = xmalloc (len + 3); /* room for "ld\0" */ + fmt = (*segment)->text = xmalloc (len + sizeof "d"); strncpy (fmt, format, len); fmt += len; @@ -1540,15 +2030,20 @@ make_segment (segment, format, len, kind) break; case 'a': /* atime in `ctime' format */ + case 'A': /* atime in user-specified strftime format */ case 'c': /* ctime in `ctime' format */ + case 'C': /* ctime in user-specified strftime format */ case 'F': /* filesystem type */ case 'g': /* group name */ + case 'i': /* inode number */ case 'l': /* object of symlink */ + case 'M': /* mode in `ls -l' format (eg., "drwxr-xr-x") */ + case 's': /* size in bytes */ case 't': /* mtime in `ctime' format */ - case 'u': /* user name */ - case 'A': /* atime in user-specified strftime format */ - case 'C': /* ctime in user-specified strftime format */ case 'T': /* mtime in user-specified strftime format */ + case 'u': /* user name */ + case 'y': /* file type */ + case 'Y': /* symlink pointed file type */ fprintf_stat_needed = true; /* FALLTHROUGH */ case 'f': /* basename of path */ @@ -1559,25 +2054,23 @@ make_segment (segment, format, len, kind) *fmt++ = 's'; break; - case 'b': /* size in 512-byte blocks */ - case 'k': /* size in 1K blocks */ - case 's': /* size in bytes */ - *fmt++ = 'l'; - /*FALLTHROUGH*/ - case 'n': /* number of links */ - fprintf_stat_needed = true; - /* FALLTHROUGH */ - case 'd': /* depth in search tree (0 = ARGV element) */ - *fmt++ = 'd'; - break; - - case 'i': /* inode number */ - *fmt++ = 'l'; - /*FALLTHROUGH*/ + /* Numeric items that one might expect to honour + * #, 0, + flags but which do not. + */ case 'G': /* GID number */ case 'U': /* UID number */ - *fmt++ = 'u'; + case 'b': /* size in 512-byte blocks */ + case 'D': /* Filesystem device on which the file exits */ + case 'k': /* size in 1K blocks */ + case 'n': /* number of links */ fprintf_stat_needed = true; + *fmt++ = 's'; + break; + + /* Numeric items that DO honour #, 0, + flags. + */ + case 'd': /* depth in search tree (0 = ARGV element) */ + *fmt++ = 'd'; break; case 'm': /* mode as octal number (perms only) */ @@ -1587,14 +2080,225 @@ make_segment (segment, format, len, kind) } *fmt = '\0'; - return (&(*segment)->next); + return &(*segment)->next; +} + +static void +check_path_safety(const char *action) +{ + const char *path = getenv("PATH"); + char *s; + s = next_element(path, 1); + while ((s = next_element ((char *) NULL, 1)) != NULL) + { + if (0 == strcmp(s, ".")) + { + error(1, 0, _("The current directory is included in the PATH environment variable, which is insecure in combination with the %s action of find. Please remove the current directory from your $PATH (that is, remove \".\" or leading or trailing colons)"), + action); + } + } } + +/* handles both exec and ok predicate */ +#if defined(NEW_EXEC) +/* handles both exec and ok predicate */ static boolean -insert_exec_ok (func, argv, arg_ptr) - boolean (*func) (); - char *argv[]; - int *arg_ptr; +new_insert_exec_ok (const char *action, + const struct parser_table *entry, + char **argv, + int *arg_ptr) +{ + int start, end; /* Indexes in ARGV of start & end of cmd. */ + int i; /* Index into cmd args */ + int saw_braces; /* True if previous arg was '{}'. */ + boolean allow_plus; /* True if + is a valid terminator */ + int brace_count; /* Number of instances of {}. */ + PRED_FUNC func = entry->pred_func; + enum BC_INIT_STATUS bcstatus; + + struct predicate *our_pred; + struct exec_val *execp; /* Pointer for efficiency. */ + + if ((argv == NULL) || (argv[*arg_ptr] == NULL)) + return false; + + our_pred = insert_primary_withpred (entry, func); + our_pred->side_effects = our_pred->no_default_print = true; + execp = &our_pred->args.exec_vec; + + if ((func != pred_okdir) && (func != pred_ok)) + { + allow_plus = true; + execp->close_stdin = false; + } + else + { + allow_plus = false; + /* If find reads stdin (i.e. for -ok and similar), close stdin + * in the child to prevent some script from consiming the output + * intended for find. + */ + execp->close_stdin = true; + } + + + if ((func == pred_execdir) || (func == pred_okdir)) + { + options.ignore_readdir_race = false; + check_path_safety(action); + execp->use_current_dir = true; + } + else + { + execp->use_current_dir = false; + } + + our_pred->args.exec_vec.multiple = 0; + + /* Count the number of args with path replacements, up until the ';'. + * Also figure out if the command is terminated by ";" or by "+". + */ + start = *arg_ptr; + for (end = start, saw_braces=0, brace_count=0; + (argv[end] != NULL) + && ((argv[end][0] != ';') || (argv[end][1] != '\0')); + end++) + { + /* For -exec and -execdir, "{} +" can terminate the command. */ + if ( allow_plus + && argv[end][0] == '+' && argv[end][1] == 0 + && saw_braces) + { + our_pred->args.exec_vec.multiple = 1; + break; + } + + saw_braces = 0; + if (strstr (argv[end], "{}")) + { + saw_braces = 1; + ++brace_count; + + if (0 == end && (func == pred_execdir || func == pred_okdir)) + { + /* The POSIX standard says that {} replacement should + * occur even in the utility name. This is insecure + * since it means we will be executing a command whose + * name is chosen according to whatever find finds in + * the filesystem. That can be influenced by an + * attacker. Hence for -execdir and -okdir this is not + * allowed. We can specify this as those options are + * not defined by POSIX. + */ + error(1, 0, _("You may not use {} within the utility name for -execdir and -okdir, because this is a potential security problem.")); + } + } + } + + /* Fail if no command given or no semicolon found. */ + if ((end == start) || (argv[end] == NULL)) + { + *arg_ptr = end; + free(our_pred); + return false; + } + + if (our_pred->args.exec_vec.multiple && brace_count > 1) + { + + const char *suffix; + if (func == pred_execdir) + suffix = "dir"; + else + suffix = ""; + + error(1, 0, + _("Only one instance of {} is supported with -exec%s ... +"), + suffix); + } + + /* We use a switch statement here so that + * the compiler warns us when we forget to handle a + * newly invented enum value. + */ + bcstatus = bc_init_controlinfo(&execp->ctl); + switch (bcstatus) + { + case BC_INIT_ENV_TOO_BIG: + error(1, 0, + _("The environment is too large for exec().")); + break; + case BC_INIT_OK: + /* Good news. Carry on. */ + break; + } + bc_use_sensible_arg_max(&execp->ctl); + + + execp->ctl.exec_callback = launch; + + if (our_pred->args.exec_vec.multiple) + { + /* "+" terminator, so we can just append our arguments after the + * command and initial arguments. + */ + execp->replace_vec = NULL; + execp->ctl.replace_pat = NULL; + execp->ctl.rplen = 0; + execp->ctl.lines_per_exec = 0; /* no limit */ + execp->ctl.args_per_exec = 0; /* no limit */ + + /* remember how many arguments there are */ + execp->ctl.initial_argc = (end-start) - 1; + + /* execp->state = xmalloc(sizeof struct buildcmd_state); */ + bc_init_state(&execp->ctl, &execp->state, execp); + + /* Gather the initial arguments. Skip the {}. */ + for (i=start; ictl, &execp->state, + argv[i], strlen(argv[i])+1, + NULL, 0, + 1); + } + } + else + { + /* Semicolon terminator - more than one {} is supported, so we + * have to do brace-replacement. + */ + execp->num_args = end - start; + + execp->ctl.replace_pat = "{}"; + execp->ctl.rplen = strlen(execp->ctl.replace_pat); + execp->ctl.lines_per_exec = 0; /* no limit */ + execp->ctl.args_per_exec = 0; /* no limit */ + execp->replace_vec = xmalloc(sizeof(char*)*execp->num_args); + + + /* execp->state = xmalloc(sizeof(*(execp->state))); */ + bc_init_state(&execp->ctl, &execp->state, execp); + + /* Remember the (pre-replacement) arguments for later. */ + for (i=0; inum_args; ++i) + { + execp->replace_vec[i] = argv[i+start]; + } + } + + if (argv[end] == NULL) + *arg_ptr = end; + else + *arg_ptr = end + 1; + + return true; +} +#else +/* handles both exec and ok predicate */ +static boolean +old_insert_exec_ok (boolean (*func) (/* ??? */), char **argv, int *arg_ptr) { int start, end; /* Indexes in ARGV of start & end of cmd. */ int num_paths; /* Number of args with path replacements. */ @@ -1604,7 +2308,7 @@ insert_exec_ok (func, argv, arg_ptr) struct exec_val *execp; /* Pointer for efficiency. */ if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; /* Count the number of args with path replacements, up until the ';'. */ start = *arg_ptr; @@ -1618,12 +2322,14 @@ insert_exec_ok (func, argv, arg_ptr) if ((end == start) || (argv[end] == NULL)) { *arg_ptr = end; - return (false); + return false; } our_pred = insert_primary (func); - our_pred->side_effects = true; + our_pred->side_effects = our_pred->no_default_print = true; execp = &our_pred->args.exec_vec; + execp->usercontext = our_pred; + execp->use_current_dir = false; execp->paths = (struct path_arg *) xmalloc (sizeof (struct path_arg) * (num_paths + 1)); execp->vec = (char **) xmalloc (sizeof (char *) * (end - start + 1)); @@ -1657,8 +2363,23 @@ insert_exec_ok (func, argv, arg_ptr) *arg_ptr = end; else *arg_ptr = end + 1; - return (true); + return true; } +#endif + + + +static boolean +insert_exec_ok (const char *action, const struct parser_table *entry, char **argv, int *arg_ptr) +{ +#if defined(NEW_EXEC) + return new_insert_exec_ok(action, entry, argv, arg_ptr); +#else + return old_insert_exec_ok(func, argv, arg_ptr); +#endif +} + + /* Get a number of days and comparison type. STR is the ASCII representation. @@ -1673,48 +2394,17 @@ insert_exec_ok (func, argv, arg_ptr) get the appropriate information for a time predicate processor. */ static boolean -get_num_days (str, num_days, comp_type) - char *str; - unsigned long *num_days; - enum comparison_type *comp_type; +get_num_days (char *str, uintmax_t *num_days, enum comparison_type *comp_type) { - int len_days; /* length of field */ - - if (str == NULL) - return (false); - switch (str[0]) - { - case '+': - *comp_type = COMP_LT; - str++; - break; - case '-': - *comp_type = COMP_GT; - str++; - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - *comp_type = COMP_EQ; - break; - default: - return (false); - } - - /* We know the first char has been reasonable. Find the - number of days to play with. */ - len_days = strspn (str, "0123456789"); - if ((len_days == 0) || (str[len_days] != '\0')) - return (false); - *num_days = (unsigned long) atol (str); - return (true); + boolean r = get_num (str, num_days, comp_type); + if (r) + switch (*comp_type) + { + case COMP_LT: *comp_type = COMP_GT; break; + case COMP_GT: *comp_type = COMP_LT; break; + default: break; + } + return r; } /* Insert a time predicate PRED. @@ -1730,66 +2420,79 @@ get_num_days (str, num_days, comp_type) Used by -atime, -ctime, and -mtime parsers. */ static boolean -insert_time (argv, arg_ptr, pred) - char *argv[]; - int *arg_ptr; - PFB pred; +insert_time (char **argv, int *arg_ptr, const struct parser_table* entry, PRED_FUNC pred) { struct predicate *our_pred; - unsigned long num_days; + uintmax_t num_days; enum comparison_type c_type; + time_t t; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; if (!get_num_days (argv[*arg_ptr], &num_days, &c_type)) - return (false); - our_pred = insert_primary (pred); + return false; + + /* Figure out the timestamp value we are looking for. */ + t = ( options.cur_day_start - num_days * DAYSECS + + ((c_type == COMP_GT) ? DAYSECS - 1 : 0)); + + if (1) + { + /* We introduce a scope in which 'val' can be declared, for the + * benefit of compilers that are really C89 compilers + * which support intmax_t because config.h #defines it + */ + intmax_t val = ( (intmax_t)options.cur_day_start - num_days * DAYSECS + + ((c_type == COMP_GT) ? DAYSECS - 1 : 0)); + t = val; + + /* Check for possibility of an overflow */ + if ( (intmax_t)t != val ) + { + error (1, 0, "arithmetic overflow while converting %s days to a number of seconds", argv[*arg_ptr]); + } + } + + our_pred = insert_primary_withpred (entry, pred); our_pred->args.info.kind = c_type; - our_pred->args.info.l_val = cur_day_start - num_days * DAYSECS - + ((c_type == COMP_GT) ? DAYSECS - 1 : 0); + our_pred->args.info.negative = t < 0; + our_pred->args.info.l_val = t; (*arg_ptr)++; #ifdef DEBUG - printf ("inserting %s\n", our_pred->p_name); - printf (" type: %s %s ", + fprintf (stderr, "inserting %s\n", our_pred->p_name); + fprintf (stderr, " type: %s %s ", (c_type == COMP_GT) ? "gt" : ((c_type == COMP_LT) ? "lt" : ((c_type == COMP_EQ) ? "eq" : "?")), (c_type == COMP_GT) ? " >" : ((c_type == COMP_LT) ? " <" : ((c_type == COMP_EQ) ? ">=" : " ?"))); - printf ("%ld %s", our_pred->args.info.l_val, - ctime (&our_pred->args.info.l_val)); + t = our_pred->args.info.l_val; + fprintf (stderr, "%ju %s", (uintmax_t) our_pred->args.info.l_val, ctime (&t)); if (c_type == COMP_EQ) { - our_pred->args.info.l_val += DAYSECS; - printf (" < %ld %s", our_pred->args.info.l_val, - ctime (&our_pred->args.info.l_val)); + t = our_pred->args.info.l_val += DAYSECS; + fprintf (stderr, " < %ju %s", + (uintmax_t) our_pred->args.info.l_val, ctime (&t)); our_pred->args.info.l_val -= DAYSECS; } #endif /* DEBUG */ - return (true); + return true; } -/* Get a number with comparision information. - The sense of the comparision information is 'normal'; that is, - '+' looks for inums or links > than the number and '-' less than. +/* Get a number with comparison information. + The sense of the comparison information is 'normal'; that is, + '+' looks for a count > than the number and '-' less than. STR is the ASCII representation of the number. Set *NUM to the number. Set *COMP_TYPE to the kind of comparison that is requested. - Return true if all okay, false if input error. - - Used by the -inum and -links predicate parsers. */ + Return true if all okay, false if input error. */ static boolean -get_num (str, num, comp_type) - char *str; - unsigned long *num; - enum comparison_type *comp_type; +get_num (char *str, uintmax_t *num, enum comparison_type *comp_type) { - int len_num; /* Length of field. */ - if (str == NULL) - return (false); + return false; switch (str[0]) { case '+': @@ -1800,29 +2503,12 @@ get_num (str, num, comp_type) *comp_type = COMP_LT; str++; break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': + default: *comp_type = COMP_EQ; break; - default: - return (false); } - /* We know the first char has been reasonable. Find the number of - days to play with. */ - len_num = strspn (str, "0123456789"); - if ((len_num == 0) || (str[len_num] != '\0')) - return (false); - *num = (unsigned long) atol (str); - return (true); + return xstrtoumax (str, NULL, 10, num, "") == LONGINT_OK; } /* Insert a number predicate. @@ -1838,47 +2524,43 @@ get_num (str, num, comp_type) Used by -inum and -links parsers. */ static boolean -insert_num (argv, arg_ptr, pred) - char *argv[]; - int *arg_ptr; - PFB pred; +insert_num (char **argv, int *arg_ptr, const struct parser_table *entry) { struct predicate *our_pred; - unsigned long num; + uintmax_t num; enum comparison_type c_type; if ((argv == NULL) || (argv[*arg_ptr] == NULL)) - return (false); + return false; if (!get_num (argv[*arg_ptr], &num, &c_type)) - return (false); - our_pred = insert_primary (pred); + return false; + our_pred = insert_primary (entry); our_pred->args.info.kind = c_type; our_pred->args.info.l_val = num; (*arg_ptr)++; #ifdef DEBUG - printf ("inserting %s\n", our_pred->p_name); - printf (" type: %s %s ", + fprintf (stderr, "inserting %s\n", our_pred->p_name); + fprintf (stderr, " type: %s %s ", (c_type == COMP_GT) ? "gt" : ((c_type == COMP_LT) ? "lt" : ((c_type == COMP_EQ) ? "eq" : "?")), (c_type == COMP_GT) ? " >" : ((c_type == COMP_LT) ? " <" : ((c_type == COMP_EQ) ? " =" : " ?"))); - printf ("%ld\n", our_pred->args.info.l_val); + fprintf (stderr, "%ju\n", our_pred->args.info.l_val); #endif /* DEBUG */ - return (true); + return true; } static FILE * -open_output_file (path) - char *path; +open_output_file (char *path) { FILE *f; if (!strcmp (path, "/dev/stderr")) - return (stderr); + return stderr; else if (!strcmp (path, "/dev/stdout")) - return (stdout); - f = fopen (path, "w"); + return stdout; + f = fopen_safer (path, "w"); if (f == NULL) error (1, errno, "%s", path); - return (f); + return f; } diff --git a/src/bin/findutils/find/pred.c b/src/bin/findutils/find/pred.c index 9c8c682852..b8a3ff9b29 100644 --- a/src/bin/findutils/find/pred.c +++ b/src/bin/findutils/find/pred.c @@ -1,40 +1,59 @@ /* pred.c -- execute the expression tree. - Copyright (C) 1990, 91, 92, 93, 94 Free Software Foundation, Inc. + Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, 2003, + 2004, 2005, 2007 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ + +#include "defs.h" -#include -#include -#include -#include #include #include #include #include -#include "defs.h" +#include +#include +#include +#include +#include "xalloc.h" +#include "dirname.h" +#include "human.h" #include "modetype.h" +#include "filemode.h" #include "wait.h" +#include "printquoted.h" +#include "buildcmd.h" +#include "yesno.h" + +#if ENABLE_NLS +# include +# define _(Text) gettext (Text) +#else +# define _(Text) Text +#endif +#ifdef gettext_noop +# define N_(String) gettext_noop (String) +#else +/* See locate.c for explanation as to why not use (String) */ +# define N_(String) String +#endif #if !defined(SIGCHLD) && defined(SIGCLD) #define SIGCHLD SIGCLD #endif -#ifndef _POSIX_VERSION -struct passwd *getpwuid (); -struct group *getgrgid (); -#endif + #if HAVE_DIRENT_H # include @@ -60,37 +79,82 @@ struct group *getgrgid (); #define CLOSEDIR(d) closedir (d) #endif -#ifndef S_IFLNK -#define lstat stat -#endif + + + +/* Get or fake the disk device blocksize. + Usually defined by sys/param.h (if at all). */ +#ifndef DEV_BSIZE +# ifdef BSIZE +# define DEV_BSIZE BSIZE +# else /* !BSIZE */ +# define DEV_BSIZE 4096 +# endif /* !BSIZE */ +#endif /* !DEV_BSIZE */ /* Extract or fake data from a `struct stat'. - ST_NBLOCKS: Number of 512-byte blocks in the file - (including indirect blocks). - HP-UX, perhaps uniquely, counts st_blocks in 1024-byte units. - This workaround loses when mixing HP-UX and 4BSD filesystems, though. */ -#ifdef _POSIX_SOURCE -# define ST_NBLOCKS(statp) (((statp)->st_size + 512 - 1) / 512) -#else -# ifndef HAVE_ST_BLOCKS -# define ST_NBLOCKS(statp) (st_blocks ((statp)->st_size)) -# else -# if defined(hpux) || defined(__hpux__) -# define ST_NBLOCKS(statp) ((statp)->st_blocks * 2) -# else -# define ST_NBLOCKS(statp) ((statp)->st_blocks) -# endif -# endif + ST_BLKSIZE: Preferred I/O blocksize for the file, in bytes. + ST_NBLOCKS: Number of blocks in the file, including indirect blocks. + ST_NBLOCKSIZE: Size of blocks used when calculating ST_NBLOCKS. */ +#ifndef HAVE_STRUCT_STAT_ST_BLOCKS +# define ST_BLKSIZE(statbuf) DEV_BSIZE +# if defined(_POSIX_SOURCE) || !defined(BSIZE) /* fileblocks.c uses BSIZE. */ +# define ST_NBLOCKS(statbuf) \ + (S_ISREG ((statbuf).st_mode) \ + || S_ISDIR ((statbuf).st_mode) \ + ? (statbuf).st_size / ST_NBLOCKSIZE + ((statbuf).st_size % ST_NBLOCKSIZE != 0) : 0) +# else /* !_POSIX_SOURCE && BSIZE */ +# define ST_NBLOCKS(statbuf) \ + (S_ISREG ((statbuf).st_mode) \ + || S_ISDIR ((statbuf).st_mode) \ + ? st_blocks ((statbuf).st_size) : 0) +# endif /* !_POSIX_SOURCE && BSIZE */ +#else /* HAVE_STRUCT_STAT_ST_BLOCKS */ +/* Some systems, like Sequents, return st_blksize of 0 on pipes. */ +# define ST_BLKSIZE(statbuf) ((statbuf).st_blksize > 0 \ + ? (statbuf).st_blksize : DEV_BSIZE) +# if defined(hpux) || defined(__hpux__) || defined(__hpux) +/* HP-UX counts st_blocks in 1024-byte units. + This loses when mixing HP-UX and BSD filesystems with NFS. */ +# define ST_NBLOCKSIZE 1024 +# else /* !hpux */ +# if defined(_AIX) && defined(_I386) +/* AIX PS/2 counts st_blocks in 4K units. */ +# define ST_NBLOCKSIZE (4 * 1024) +# else /* not AIX PS/2 */ +# if defined(_CRAY) +# define ST_NBLOCKS(statbuf) \ + (S_ISREG ((statbuf).st_mode) \ + || S_ISDIR ((statbuf).st_mode) \ + ? (statbuf).st_blocks * ST_BLKSIZE(statbuf)/ST_NBLOCKSIZE : 0) +# endif /* _CRAY */ +# endif /* not AIX PS/2 */ +# endif /* !hpux */ +#endif /* HAVE_STRUCT_STAT_ST_BLOCKS */ + +#ifndef ST_NBLOCKS +# define ST_NBLOCKS(statbuf) \ + (S_ISREG ((statbuf).st_mode) \ + || S_ISDIR ((statbuf).st_mode) \ + ? (statbuf).st_blocks : 0) #endif -int lstat (); -int stat (); +#ifndef ST_NBLOCKSIZE +# define ST_NBLOCKSIZE 512 +#endif -static boolean insert_lname P_((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, boolean ignore_case)); -static boolean launch P_((struct predicate *pred_ptr)); -static char *format_date P_((time_t when, int kind)); + +#undef MAX +#define MAX(a, b) ((a) > (b) ? (a) : (b)) + +static boolean insert_lname PARAMS((char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, boolean ignore_case)); + +static char *format_date PARAMS((time_t when, int kind)); +static char *ctime_format PARAMS((time_t when)); #ifdef DEBUG +typedef boolean (*PFB) (char *, struct stat *, struct predicate *); + struct pred_assoc { PFB pred_func; @@ -103,13 +167,15 @@ struct pred_assoc pred_table[] = {pred_and, "and "}, {pred_anewer, "anewer "}, {pred_atime, "atime "}, - {pred_close, ") "}, + {pred_closeparen, ") "}, {pred_amin, "cmin "}, {pred_cnewer, "cnewer "}, {pred_comma, ", "}, {pred_ctime, "ctime "}, + {pred_delete, "delete "}, {pred_empty, "empty "}, {pred_exec, "exec "}, + {pred_execdir, "execdir "}, {pred_false, "false "}, {pred_fprint, "fprint "}, {pred_fprint0, "fprint0 "}, @@ -132,7 +198,8 @@ struct pred_assoc pred_table[] = {pred_nogroup, "nogroup "}, {pred_nouser, "nouser "}, {pred_ok, "ok "}, - {pred_open, "( "}, + {pred_okdir, "okdir "}, + {pred_openparen, "( "}, {pred_or, "or "}, {pred_path, "path "}, {pred_perm, "perm "}, @@ -140,6 +207,7 @@ struct pred_assoc pred_table[] = {pred_print0, "print0 "}, {pred_prune, "prune "}, {pred_regex, "regex "}, + {pred_samefile,"samefile "}, {pred_size, "size "}, {pred_true, "true "}, {pred_type, "type "}, @@ -193,53 +261,55 @@ struct prec_assoc prec_table[] = Return true if the file passes this predicate, false if not. */ -boolean -pred_amin (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; + +/* pred_timewindow + * + * Returns true if THE_TIME is + * COMP_GT: after the specified time + * COMP_LT: before the specified time + * COMP_EQ: less than WINDOW seconds after the specified time. + */ +static boolean +pred_timewindow(time_t the_time, struct predicate const *pred_ptr, int window) { switch (pred_ptr->args.info.kind) { case COMP_GT: - if (stat_buf->st_atime > (time_t) pred_ptr->args.info.l_val) - return (true); + if (the_time > (time_t) pred_ptr->args.info.l_val) + return true; break; case COMP_LT: - if (stat_buf->st_atime < (time_t) pred_ptr->args.info.l_val) - return (true); + if (the_time < (time_t) pred_ptr->args.info.l_val) + return true; break; case COMP_EQ: - if ((stat_buf->st_atime >= (time_t) pred_ptr->args.info.l_val) - && (stat_buf->st_atime < (time_t) pred_ptr->args.info.l_val + 60)) - return (true); + if ((the_time >= (time_t) pred_ptr->args.info.l_val) + && (the_time < (time_t) pred_ptr->args.info.l_val + window)) + return true; break; } - return (false); + return false; +} + + +boolean +pred_amin (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) +{ + (void) &pathname; + return pred_timewindow(stat_buf->st_atime, pred_ptr, 60); } boolean -pred_and (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_and (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { if (pred_ptr->pred_left == NULL || (*pred_ptr->pred_left->pred_func) (pathname, stat_buf, pred_ptr->pred_left)) { /* Check whether we need a stat here. */ - if (pred_ptr->need_stat) - { - if (!have_stat && (*xstat) (rel_pathname, stat_buf) != 0) - { - error (0, errno, "%s", pathname); - exit_status = 1; - return (false); - } - have_stat = true; - } - return ((*pred_ptr->pred_right->pred_func) (pathname, stat_buf, + if (get_info(pathname, state.rel_pathname, stat_buf, pred_ptr) != 0) + return false; + return ((*pred_ptr->pred_right->pred_func) (pathname, stat_buf, pred_ptr->pred_right)); } else @@ -247,143 +317,99 @@ pred_and (pathname, stat_buf, pred_ptr) } boolean -pred_anewer (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_anewer (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) &pathname; + if (stat_buf->st_atime > pred_ptr->args.time) return (true); return (false); } boolean -pred_atime (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_atime (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - switch (pred_ptr->args.info.kind) - { - case COMP_GT: - if (stat_buf->st_atime > (time_t) pred_ptr->args.info.l_val) - return (true); - break; - case COMP_LT: - if (stat_buf->st_atime < (time_t) pred_ptr->args.info.l_val) - return (true); - break; - case COMP_EQ: - if ((stat_buf->st_atime >= (time_t) pred_ptr->args.info.l_val) - && (stat_buf->st_atime < (time_t) pred_ptr->args.info.l_val - + DAYSECS)) - return (true); - break; - } - return (false); + (void) &pathname; + return pred_timewindow(stat_buf->st_atime, pred_ptr, DAYSECS); } boolean -pred_close (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_closeparen (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - return (true); + (void) &pathname; + (void) &stat_buf; + (void) &pred_ptr; + + return true; } boolean -pred_cmin (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_cmin (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - switch (pred_ptr->args.info.kind) - { - case COMP_GT: - if (stat_buf->st_ctime > (time_t) pred_ptr->args.info.l_val) - return (true); - break; - case COMP_LT: - if (stat_buf->st_ctime < (time_t) pred_ptr->args.info.l_val) - return (true); - break; - case COMP_EQ: - if ((stat_buf->st_ctime >= (time_t) pred_ptr->args.info.l_val) - && (stat_buf->st_ctime < (time_t) pred_ptr->args.info.l_val + 60)) - return (true); - break; - } - return (false); + (void) pathname; + return pred_timewindow(stat_buf->st_ctime, pred_ptr, 60); } boolean -pred_cnewer (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_cnewer (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) pathname; + if (stat_buf->st_ctime > pred_ptr->args.time) - return (true); - return (false); + return true; + else + return false; } boolean -pred_comma (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_comma (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { if (pred_ptr->pred_left != NULL) (*pred_ptr->pred_left->pred_func) (pathname, stat_buf, pred_ptr->pred_left); /* Check whether we need a stat here. */ - if (pred_ptr->need_stat) - { - if (!have_stat && (*xstat) (rel_pathname, stat_buf) != 0) - { - error (0, errno, "%s", pathname); - exit_status = 1; - return (false); - } - have_stat = true; - } + /* TODO: what about need_type? */ + if (get_info(pathname, state.rel_pathname, stat_buf, pred_ptr) != 0) + return false; return ((*pred_ptr->pred_right->pred_func) (pathname, stat_buf, pred_ptr->pred_right)); } boolean -pred_ctime (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_ctime (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - switch (pred_ptr->args.info.kind) - { - case COMP_GT: - if (stat_buf->st_ctime > (time_t) pred_ptr->args.info.l_val) - return (true); - break; - case COMP_LT: - if (stat_buf->st_ctime < (time_t) pred_ptr->args.info.l_val) - return (true); - break; - case COMP_EQ: - if ((stat_buf->st_ctime >= (time_t) pred_ptr->args.info.l_val) - && (stat_buf->st_ctime < (time_t) pred_ptr->args.info.l_val - + DAYSECS)) - return (true); - break; - } - return (false); + (void) &pathname; + return pred_timewindow(stat_buf->st_ctime, pred_ptr, DAYSECS); } boolean -pred_empty (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_delete (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) pred_ptr; + (void) stat_buf; + if (strcmp (state.rel_pathname, ".")) + { + if (0 != remove (state.rel_pathname)) + { + error (0, errno, "cannot delete %s", pathname); + return false; + } + else + { + return true; + } + } + + /* nothing to do. */ + return true; +} + +boolean +pred_empty (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) +{ + (void) pathname; + (void) pred_ptr; + if (S_ISDIR (stat_buf->st_mode)) { DIR *d; @@ -391,12 +417,12 @@ pred_empty (pathname, stat_buf, pred_ptr) boolean empty = true; errno = 0; - d = opendir (rel_pathname); + d = opendir (state.rel_pathname); if (d == NULL) { error (0, errno, "%s", pathname); - exit_status = 1; - return (false); + state.exit_status = 1; + return false; } for (dp = readdir (d); dp; dp = readdir (d)) { @@ -411,8 +437,8 @@ pred_empty (pathname, stat_buf, pred_ptr) if (CLOSEDIR (d)) { error (0, errno, "%s", pathname); - exit_status = 1; - return (false); + state.exit_status = 1; + return false; } return (empty); } @@ -422,97 +448,142 @@ pred_empty (pathname, stat_buf, pred_ptr) return (false); } -boolean -pred_exec (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +static boolean +new_impl_pred_exec (const char *pathname, struct stat *stat_buf, + struct predicate *pred_ptr, + const char *prefix, size_t pfxlen) { - int i; - int path_pos; - struct exec_val *execp; /* Pointer for efficiency. */ + struct exec_val *execp = &pred_ptr->args.exec_vec; + size_t len = strlen(pathname); - execp = &pred_ptr->args.exec_vec; - - /* Replace "{}" with the real path in each affected arg. */ - for (path_pos = 0; execp->paths[path_pos].offset >= 0; path_pos++) + (void) stat_buf; + + if (execp->multiple) { - register char *from, *to; - - i = execp->paths[path_pos].offset; - execp->vec[i] = - xmalloc (strlen (execp->paths[path_pos].origarg) + 1 - + (strlen (pathname) - 2) * execp->paths[path_pos].count); - for (from = execp->paths[path_pos].origarg, to = execp->vec[i]; *from; ) - if (from[0] == '{' && from[1] == '}') - { - to = stpcpy (to, pathname); - from += 2; - } - else - *to++ = *from++; - *to = *from; /* Copy null. */ + /* Push the argument onto the current list. + * The command may or may not be run at this point, + * depending on the command line length limits. + */ + bc_push_arg(&execp->ctl, + &execp->state, + pathname, len+1, + prefix, pfxlen, + 0); + + /* POSIX: If the primary expression is punctuated by a plus + * sign, the primary shall always evaluate as true + */ + return true; } + else + { + int i; - i = launch (pred_ptr); + for (i=0; inum_args; ++i) + { + bc_do_insert(&execp->ctl, + &execp->state, + execp->replace_vec[i], + strlen(execp->replace_vec[i]), + prefix, pfxlen, + pathname, len, + 0); + } - /* Free the temporary args. */ - for (path_pos = 0; execp->paths[path_pos].offset >= 0; path_pos++) - free (execp->vec[execp->paths[path_pos].offset]); + /* Actually invoke the command. */ + return execp->ctl.exec_callback(&execp->ctl, + &execp->state); + } +} - return (i); + +boolean +pred_exec (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) +{ + return new_impl_pred_exec(pathname, stat_buf, pred_ptr, NULL, 0); } boolean -pred_false (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_execdir (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./"; + (void) &pathname; + return new_impl_pred_exec (state.rel_pathname, stat_buf, pred_ptr, + prefix, (prefix ? 2 : 0)); +} + +boolean +pred_false (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) +{ + (void) &pathname; + (void) &stat_buf; + (void) &pred_ptr; + + return (false); } boolean -pred_fls (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_fls (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - list_file (pathname, rel_pathname, stat_buf, pred_ptr->args.stream); + list_file (pathname, state.rel_pathname, stat_buf, options.start_time, + options.output_block_size, pred_ptr->args.stream); return (true); } boolean -pred_fprint (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_fprint (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - fputs (pathname, pred_ptr->args.stream); - putc ('\n', pred_ptr->args.stream); - return (true); + (void) &pathname; + (void) &stat_buf; + + print_quoted(pred_ptr->args.printf_vec.stream, + pred_ptr->args.printf_vec.quote_opts, + pred_ptr->args.printf_vec.dest_is_tty, + "%s\n", + pathname); + return true; } boolean -pred_fprint0 (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_fprint0 (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) &pathname; + (void) &stat_buf; + fputs (pathname, pred_ptr->args.stream); putc (0, pred_ptr->args.stream); return (true); } + + +static char* +mode_to_filetype(mode_t m) +{ + return + m == S_IFSOCK ? "s" : + m == S_IFLNK ? "l" : + m == S_IFREG ? "f" : + m == S_IFBLK ? "b" : + m == S_IFDIR ? "d" : + m == S_IFCHR ? "c" : +#ifdef S_IFDOOR + m == S_IFDOOR ? "D" : +#endif + m == S_IFIFO ? "p" : "U"; +} + + boolean -pred_fprintf (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_fprintf (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { FILE *fp = pred_ptr->args.printf_vec.stream; + const struct quoting_options *qopts = pred_ptr->args.printf_vec.quote_opts; + boolean ttyflag = pred_ptr->args.printf_vec.dest_is_tty; struct segment *segment; char *cp; + char hbuf[LONGEST_HUMAN_READABLE + 1]; for (segment = pred_ptr->args.printf_vec.segment; segment; segment = segment->next) @@ -535,6 +606,11 @@ pred_fprintf (pathname, stat_buf, pred_ptr) default: abort (); } + /* We trust the output of format_date not to contain + * nasty characters, though the value of the date + * is itself untrusted data. + */ + /* trusted */ fprintf (fp, segment->text, format_date (t, (segment->kind >> 8) & 0xff)); continue; @@ -543,41 +619,56 @@ pred_fprintf (pathname, stat_buf, pred_ptr) switch (segment->kind) { case KIND_PLAIN: /* Plain text string (no % conversion). */ + /* trusted */ fwrite (segment->text, 1, segment->text_len, fp); break; case KIND_STOP: /* Terminate argument and flush output. */ + /* trusted */ fwrite (segment->text, 1, segment->text_len, fp); fflush (fp); return (true); case 'a': /* atime in `ctime' format. */ - cp = ctime (&stat_buf->st_atime); - cp[24] = '\0'; - fprintf (fp, segment->text, cp); + /* UNTRUSTED, probably unexploitable */ + fprintf (fp, segment->text, ctime_format (stat_buf->st_atime)); break; case 'b': /* size in 512-byte blocks */ - fprintf (fp, segment->text, ST_NBLOCKS (stat_buf)); + /* UNTRUSTED, probably unexploitable */ + fprintf (fp, segment->text, + human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf), + hbuf, human_ceiling, + ST_NBLOCKSIZE, 512)); break; case 'c': /* ctime in `ctime' format */ - cp = ctime (&stat_buf->st_ctime); - cp[24] = '\0'; - fprintf (fp, segment->text, cp); + /* UNTRUSTED, probably unexploitable */ + fprintf (fp, segment->text, ctime_format (stat_buf->st_ctime)); break; case 'd': /* depth in search tree */ - fprintf (fp, segment->text, curdepth); + /* UNTRUSTED, probably unexploitable */ + fprintf (fp, segment->text, state.curdepth); break; - case 'f': /* basename of path */ - cp = strrchr (pathname, '/'); - if (cp) - cp++; - else - cp = pathname; - fprintf (fp, segment->text, cp); + case 'D': /* Device on which file exists (stat.st_dev) */ + /* trusted */ + fprintf (fp, segment->text, + human_readable ((uintmax_t) stat_buf->st_dev, hbuf, + human_ceiling, 1, 1)); + break; + case 'f': /* base name of path */ + /* sanitised */ + { + char *base = base_name (pathname); + print_quoted (fp, qopts, ttyflag, segment->text, base); + free (base); + } break; case 'F': /* filesystem type */ - fprintf (fp, segment->text, - filesystem_type (pathname, rel_pathname, stat_buf)); + /* trusted */ + print_quoted (fp, qopts, ttyflag, segment->text, filesystem_type (stat_buf, pathname)); break; case 'g': /* group name */ + /* trusted */ + /* (well, the actual group is selected by the user but + * its name was selected by the system administrator) + */ { struct group *g; @@ -591,71 +682,139 @@ pred_fprintf (pathname, stat_buf, pred_ptr) /* else fallthru */ } case 'G': /* GID number */ - segment->text[segment->text_len] = 'u'; - fprintf (fp, segment->text, stat_buf->st_gid); + /* UNTRUSTED, probably unexploitable */ + fprintf (fp, segment->text, + human_readable ((uintmax_t) stat_buf->st_gid, hbuf, + human_ceiling, 1, 1)); break; case 'h': /* leading directories part of path */ + /* sanitised */ { char cc; - + cp = strrchr (pathname, '/'); if (cp == NULL) /* No leading directories. */ - break; - cc = *cp; - *cp = '\0'; - fprintf (fp, segment->text, pathname); - *cp = cc; + { + /* If there is no slash in the pathname, we still + * print the string because it contains characters + * other than just '%s'. The %h expands to ".". + */ + print_quoted (fp, qopts, ttyflag, segment->text, "."); + } + else + { + cc = *cp; + *cp = '\0'; + print_quoted (fp, qopts, ttyflag, segment->text, pathname); + *cp = cc; + } break; } case 'H': /* ARGV element file was found under */ + /* trusted */ { - char cc = pathname[path_length]; + char cc = pathname[state.path_length]; - pathname[path_length] = '\0'; + pathname[state.path_length] = '\0'; fprintf (fp, segment->text, pathname); - pathname[path_length] = cc; + pathname[state.path_length] = cc; break; } case 'i': /* inode number */ - fprintf (fp, segment->text, stat_buf->st_ino); + /* UNTRUSTED, but not exploitable I think */ + fprintf (fp, segment->text, + human_readable ((uintmax_t) stat_buf->st_ino, hbuf, + human_ceiling, + 1, 1)); break; case 'k': /* size in 1K blocks */ - fprintf (fp, segment->text, (ST_NBLOCKS (stat_buf) + 1) / 2); + /* UNTRUSTED, but not exploitable I think */ + fprintf (fp, segment->text, + human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf), + hbuf, human_ceiling, + ST_NBLOCKSIZE, 1024)); break; case 'l': /* object of symlink */ + /* sanitised */ #ifdef S_ISLNK { char *linkname = 0; if (S_ISLNK (stat_buf->st_mode)) { - linkname = get_link_name (pathname, rel_pathname); + linkname = get_link_name (pathname, state.rel_pathname); if (linkname == 0) - exit_status = 1; + state.exit_status = 1; } if (linkname) { - fprintf (fp, segment->text, linkname); + print_quoted (fp, qopts, ttyflag, segment->text, linkname); free (linkname); } else - fprintf (fp, segment->text, ""); + print_quoted (fp, qopts, ttyflag, segment->text, ""); } #endif /* S_ISLNK */ break; - case 'm': /* mode as octal number (perms only) */ - fprintf (fp, segment->text, stat_buf->st_mode & 07777); + + case 'M': /* mode as 10 chars (eg., "-rwxr-x--x" */ + /* UNTRUSTED, probably unexploitable */ + { + char modestring[16] ; + filemodestring (stat_buf, modestring); + modestring[10] = '\0'; + fprintf (fp, segment->text, modestring); + } break; + + case 'm': /* mode as octal number (perms only) */ + /* UNTRUSTED, probably unexploitable */ + { + /* Output the mode portably using the traditional numbers, + even if the host unwisely uses some other numbering + scheme. But help the compiler in the common case where + the host uses the traditional numbering scheme. */ + mode_t m = stat_buf->st_mode; + boolean traditional_numbering_scheme = + (S_ISUID == 04000 && S_ISGID == 02000 && S_ISVTX == 01000 + && S_IRUSR == 00400 && S_IWUSR == 00200 && S_IXUSR == 00100 + && S_IRGRP == 00040 && S_IWGRP == 00020 && S_IXGRP == 00010 + && S_IROTH == 00004 && S_IWOTH == 00002 && S_IXOTH == 00001); + fprintf (fp, segment->text, + (traditional_numbering_scheme + ? m & MODE_ALL + : ((m & S_ISUID ? 04000 : 0) + | (m & S_ISGID ? 02000 : 0) + | (m & S_ISVTX ? 01000 : 0) + | (m & S_IRUSR ? 00400 : 0) + | (m & S_IWUSR ? 00200 : 0) + | (m & S_IXUSR ? 00100 : 0) + | (m & S_IRGRP ? 00040 : 0) + | (m & S_IWGRP ? 00020 : 0) + | (m & S_IXGRP ? 00010 : 0) + | (m & S_IROTH ? 00004 : 0) + | (m & S_IWOTH ? 00002 : 0) + | (m & S_IXOTH ? 00001 : 0)))); + } + break; + case 'n': /* number of links */ - fprintf (fp, segment->text, stat_buf->st_nlink); + /* UNTRUSTED, probably unexploitable */ + fprintf (fp, segment->text, + human_readable ((uintmax_t) stat_buf->st_nlink, + hbuf, + human_ceiling, + 1, 1)); break; case 'p': /* pathname */ - fprintf (fp, segment->text, pathname); + /* sanitised */ + print_quoted (fp, qopts, ttyflag, segment->text, pathname); break; case 'P': /* pathname with ARGV element stripped */ - if (curdepth) + /* sanitised */ + if (state.curdepth > 0) { - cp = pathname + path_length; + cp = pathname + state.path_length; if (*cp == '/') /* Move past the slash between the ARGV element and the rest of the pathname. But if the ARGV element @@ -665,17 +824,24 @@ pred_fprintf (pathname, stat_buf, pred_ptr) } else cp = ""; - fprintf (fp, segment->text, cp); + print_quoted (fp, qopts, ttyflag, segment->text, cp); break; case 's': /* size in bytes */ - fprintf (fp, segment->text, stat_buf->st_size); + /* UNTRUSTED, probably unexploitable */ + fprintf (fp, segment->text, + human_readable ((uintmax_t) stat_buf->st_size, + hbuf, human_ceiling, 1, 1)); break; case 't': /* mtime in `ctime' format */ - cp = ctime (&stat_buf->st_mtime); - cp[24] = '\0'; - fprintf (fp, segment->text, cp); + /* UNTRUSTED, probably unexploitable */ + fprintf (fp, segment->text, ctime_format (stat_buf->st_mtime)); break; case 'u': /* user name */ + /* trusted */ + /* (well, the actual user is selected by the user on systems + * where chown is not restricted, but the user name was + * selected by the system administrator) + */ { struct passwd *p; @@ -688,33 +854,80 @@ pred_fprintf (pathname, stat_buf, pred_ptr) } /* else fallthru */ } + case 'U': /* UID number */ - segment->text[segment->text_len] = 'u'; - fprintf (fp, segment->text, stat_buf->st_uid); + /* UNTRUSTED, probably unexploitable */ + fprintf (fp, segment->text, + human_readable ((uintmax_t) stat_buf->st_uid, hbuf, + human_ceiling, 1, 1)); + break; + + /* type of filesystem entry like `ls -l`: (d,-,l,s,p,b,c,n) n=nonexistent(symlink) */ + case 'Y': /* in case of symlink */ + /* trusted */ + { +#ifdef S_ISLNK + if (S_ISLNK (stat_buf->st_mode)) + { + struct stat sbuf; + /* If we would normally follow links, do not do so. + * If we would normally not follow links, do so. + */ + if ((following_links() ? lstat : stat) + (state.rel_pathname, &sbuf) != 0) + { + if ( errno == ENOENT ) { + fprintf (fp, segment->text, "N"); + break; + }; + if ( errno == ELOOP ) { + fprintf (fp, segment->text, "L"); + break; + }; + error (0, errno, "%s", pathname); + /* exit_status = 1; + return (false); */ + } + fprintf (fp, segment->text, + mode_to_filetype(sbuf.st_mode & S_IFMT)); + } +#endif /* S_ISLNK */ + else + { + fprintf (fp, segment->text, + mode_to_filetype(stat_buf->st_mode & S_IFMT)); + } + } + break; + + case 'y': + /* trusted */ + { + fprintf (fp, segment->text, + mode_to_filetype(stat_buf->st_mode & S_IFMT)); + } break; } } - return (true); + return true; } boolean -pred_fstype (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_fstype (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - if (strcmp (filesystem_type (pathname, rel_pathname, stat_buf), - pred_ptr->args.str) == 0) - return (true); - return (false); + (void) pathname; + + if (strcmp (filesystem_type (stat_buf, pathname), pred_ptr->args.str) == 0) + return true; + else + return false; } boolean -pred_gid (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_gid (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) pathname; + switch (pred_ptr->args.info.kind) { case COMP_GT: @@ -734,11 +947,10 @@ pred_gid (pathname, stat_buf, pred_ptr) } boolean -pred_group (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_group (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) pathname; + if (pred_ptr->args.gid == stat_buf->st_gid) return (true); else @@ -746,34 +958,51 @@ pred_group (pathname, stat_buf, pred_ptr) } boolean -pred_ilname (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_ilname (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { return insert_lname (pathname, stat_buf, pred_ptr, true); } -boolean -pred_iname (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +/* Common code between -name, -iname. PATHNAME is being visited, STR + is name to compare basename against, and FLAGS are passed to + fnmatch. Recall that 'find / -name /' is one of the few times where a '/' + in the -name must actually find something. */ +static boolean +pred_name_common (const char *pathname, const char *str, int flags) { - char *base; + char *p; + boolean b; + /* We used to use last_component() here, but that would not allow us + * to modify the input string, which is const. We could optimise by + * duplicating the string only if we need to modify it, and I'll do + * that if there is a measurable performance difference on a machine + * built after 1990... + */ + char *base = base_name (pathname); + /* remove trailing slashes, but leave "/" or "//foo" unchanged. */ + strip_trailing_slashes(base); - base = basename (pathname); - if (fnmatch (pred_ptr->args.str, base, FNM_PERIOD | FNM_CASEFOLD) == 0) - return (true); - return (false); + /* FNM_PERIOD is not used here because POSIX requires that it not be. + * See http://standards.ieee.org/reading/ieee/interp/1003-2-92_int/pasc-1003.2-126.html + */ + b = fnmatch (str, base, flags) == 0; + free (base); + return b; +} + + +boolean +pred_iname (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) +{ + (void) stat_buf; + return pred_name_common (pathname, pred_ptr->args.str, FNM_CASEFOLD); } boolean -pred_inum (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_inum (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) pathname; + switch (pred_ptr->args.info.kind) { case COMP_GT: @@ -793,22 +1022,20 @@ pred_inum (pathname, stat_buf, pred_ptr) } boolean -pred_ipath (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_ipath (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) stat_buf; + if (fnmatch (pred_ptr->args.str, pathname, FNM_CASEFOLD) == 0) return (true); return (false); } boolean -pred_links (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_links (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) pathname; + switch (pred_ptr->args.info.kind) { case COMP_GT: @@ -828,26 +1055,19 @@ pred_links (pathname, stat_buf, pred_ptr) } boolean -pred_lname (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_lname (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { return insert_lname (pathname, stat_buf, pred_ptr, false); } static boolean -insert_lname (pathname, stat_buf, pred_ptr, ignore_case) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; - boolean ignore_case; +insert_lname (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, boolean ignore_case) { boolean ret = false; #ifdef S_ISLNK if (S_ISLNK (stat_buf->st_mode)) { - char *linkname = get_link_name (pathname, rel_pathname); + char *linkname = get_link_name (pathname, state.rel_pathname); if (linkname) { if (fnmatch (pred_ptr->args.str, linkname, @@ -861,118 +1081,63 @@ insert_lname (pathname, stat_buf, pred_ptr, ignore_case) } boolean -pred_ls (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_ls (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - list_file (pathname, rel_pathname, stat_buf, stdout); + (void) pred_ptr; + + list_file (pathname, state.rel_pathname, stat_buf, options.start_time, + options.output_block_size, stdout); return (true); } boolean -pred_mmin (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_mmin (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - switch (pred_ptr->args.info.kind) - { - case COMP_GT: - if (stat_buf->st_mtime > (time_t) pred_ptr->args.info.l_val) - return (true); - break; - case COMP_LT: - if (stat_buf->st_mtime < (time_t) pred_ptr->args.info.l_val) - return (true); - break; - case COMP_EQ: - if ((stat_buf->st_mtime >= (time_t) pred_ptr->args.info.l_val) - && (stat_buf->st_mtime < (time_t) pred_ptr->args.info.l_val + 60)) - return (true); - break; - } - return (false); + (void) &pathname; + return pred_timewindow(stat_buf->st_mtime, pred_ptr, 60); } boolean -pred_mtime (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_mtime (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - switch (pred_ptr->args.info.kind) - { - case COMP_GT: - if (stat_buf->st_mtime > (time_t) pred_ptr->args.info.l_val) - return (true); - break; - case COMP_LT: - if (stat_buf->st_mtime < (time_t) pred_ptr->args.info.l_val) - return (true); - break; - case COMP_EQ: - if ((stat_buf->st_mtime >= (time_t) pred_ptr->args.info.l_val) - && (stat_buf->st_mtime < (time_t) pred_ptr->args.info.l_val - + DAYSECS)) - return (true); - break; - } - return (false); + (void) pathname; + return pred_timewindow(stat_buf->st_mtime, pred_ptr, DAYSECS); } boolean -pred_name (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_name (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - char *base; - - base = basename (pathname); - if (fnmatch (pred_ptr->args.str, base, FNM_PERIOD) == 0) - return (true); - return (false); + (void) stat_buf; + return pred_name_common (pathname, pred_ptr->args.str, 0); } boolean -pred_negate (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_negate (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { /* Check whether we need a stat here. */ - if (pred_ptr->need_stat) - { - if (!have_stat && (*xstat) (rel_pathname, stat_buf) != 0) - { - error (0, errno, "%s", pathname); - exit_status = 1; - return (false); - } - have_stat = true; - } + /* TODO: what about need_type? */ + if (get_info(pathname, state.rel_pathname, stat_buf, pred_ptr) != 0) + return false; return (!(*pred_ptr->pred_right->pred_func) (pathname, stat_buf, pred_ptr->pred_right)); } boolean -pred_newer (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_newer (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) pathname; + if (stat_buf->st_mtime > pred_ptr->args.time) return (true); return (false); } boolean -pred_nogroup (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_nogroup (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) pathname; + (void) pred_ptr; + #ifdef CACHE_IDS extern char *gid_unused; @@ -983,157 +1148,187 @@ pred_nogroup (pathname, stat_buf, pred_ptr) } boolean -pred_nouser (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_nouser (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { #ifdef CACHE_IDS extern char *uid_unused; - +#endif + + (void) pathname; + (void) pred_ptr; + +#ifdef CACHE_IDS return uid_unused[(unsigned) stat_buf->st_uid]; #else return getpwuid (stat_buf->st_uid) == NULL; #endif } -boolean -pred_ok (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; + +static boolean +is_ok(const char *program, const char *arg) { - int i, yes; - fflush (stdout); - fprintf (stderr, "< %s ... %s > ? ", - pred_ptr->args.exec_vec.vec[0], pathname); + /* The draft open standard requires that, in the POSIX locale, + the last non-blank character of this prompt be '?'. + The exact format is not specified. + This standard does not have requirements for locales other than POSIX + */ + /* XXX: printing UNTRUSTED data here. */ + fprintf (stderr, _("< %s ... %s > ? "), program, arg); fflush (stderr); - i = getchar (); - yes = (i == 'y' || i == 'Y'); - while (i != EOF && i != '\n') - i = getchar (); - if (!yes) - return (false); - return pred_exec (pathname, stat_buf, pred_ptr); + return yesno(); } boolean -pred_open (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_ok (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - return (true); + if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname)) + return new_impl_pred_exec (pathname, stat_buf, pred_ptr, NULL, 0); + else + return false; } boolean -pred_or (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_okdir (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) +{ + const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./"; + if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname)) + return new_impl_pred_exec (state.rel_pathname, stat_buf, pred_ptr, + prefix, (prefix ? 2 : 0)); + else + return false; +} + +boolean +pred_openparen (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) +{ + (void) pathname; + (void) stat_buf; + (void) pred_ptr; + return true; +} + +boolean +pred_or (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { if (pred_ptr->pred_left == NULL || !(*pred_ptr->pred_left->pred_func) (pathname, stat_buf, pred_ptr->pred_left)) { - /* Check whether we need a stat here. */ - if (pred_ptr->need_stat) - { - if (!have_stat && (*xstat) (rel_pathname, stat_buf) != 0) - { - error (0, errno, "%s", pathname); - exit_status = 1; - return (false); - } - have_stat = true; - } + if (get_info(pathname, state.rel_pathname, stat_buf, pred_ptr) != 0) + return false; return ((*pred_ptr->pred_right->pred_func) (pathname, stat_buf, pred_ptr->pred_right)); } else - return (true); + return true; } boolean -pred_path (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_path (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) stat_buf; if (fnmatch (pred_ptr->args.str, pathname, 0) == 0) return (true); return (false); } boolean -pred_perm (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_perm (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - if (pred_ptr->args.perm & 010000) + mode_t mode = stat_buf->st_mode; + mode_t perm_val = pred_ptr->args.perm.val[S_ISDIR (mode) != 0]; + (void) pathname; + switch (pred_ptr->args.perm.kind) { - /* Magic flag set in parse_perm: - true if at least the given bits are set. */ - if ((stat_buf->st_mode & 07777 & pred_ptr->args.perm) - == (pred_ptr->args.perm & 07777)) - return (true); + case PERM_AT_LEAST: + return (mode & perm_val) == perm_val; + break; + + case PERM_ANY: + /* True if any of the bits set in the mask are also set in the file's mode. + * + * + * Otherwise, if onum is prefixed by a hyphen, the primary shall + * evaluate as true if at least all of the bits specified in + * onum that are also set in the octal mask 07777 are set. + * + * Eric Blake's interpretation is that the mode argument is zero, + + */ + if (0 == perm_val) + return true; /* Savannah bug 14748; we used to return false */ + else + return (mode & perm_val) != 0; + break; + + case PERM_EXACT: + return (mode & MODE_ALL) == perm_val; + break; + + default: + abort (); + break; } - else if (pred_ptr->args.perm & 020000) - { - /* Magic flag set in parse_perm: - true if any of the given bits are set. */ - if ((stat_buf->st_mode & 07777) & pred_ptr->args.perm) - return (true); - } - else - { - /* True if exactly the given bits are set. */ - if ((stat_buf->st_mode & 07777) == pred_ptr->args.perm) - return (true); - } - return (false); } boolean -pred_print (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_print (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - puts (pathname); - return (true); + (void) stat_buf; + (void) pred_ptr; + /* puts (pathname); */ + print_quoted(pred_ptr->args.printf_vec.stream, + pred_ptr->args.printf_vec.quote_opts, + pred_ptr->args.printf_vec.dest_is_tty, + "%s\n", pathname); + return true; } boolean -pred_print0 (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_print0 (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) stat_buf; + (void) pred_ptr; fputs (pathname, stdout); putc (0, stdout); return (true); } boolean -pred_prune (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_prune (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - stop_at_current_level = true; - return (do_dir_first); /* This is what SunOS find seems to do. */ + (void) pathname; + (void) stat_buf; + (void) pred_ptr; + state.stop_at_current_level = true; + return (options.do_dir_first); /* This is what SunOS find seems to do. */ } boolean -pred_regex (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_quit (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) +{ + (void) pathname; + (void) stat_buf; + (void) pred_ptr; + + /* Run any cleanups. This includes executing any command lines + * we have partly built but not executed. + */ + cleanup(); + + /* Since -exec and friends don't leave child processes running in the + * background, there is no need to wait for them here. + */ + exit(state.exit_status); /* 0 for success, etc. */ +} + +boolean +pred_regex (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { int len = strlen (pathname); +(void) stat_buf; if (re_match (pred_ptr->args.regex, pathname, len, 0, (struct re_registers *) NULL) == len) return (true); @@ -1141,15 +1336,13 @@ pred_regex (pathname, stat_buf, pred_ptr) } boolean -pred_size (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_size (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - unsigned long f_val; + uintmax_t f_val; - f_val = (stat_buf->st_size + pred_ptr->args.size.blocksize - 1) - / pred_ptr->args.size.blocksize; + (void) pathname; + f_val = ((stat_buf->st_size / pred_ptr->args.size.blocksize) + + (stat_buf->st_size % pred_ptr->args.size.blocksize != 0)); switch (pred_ptr->args.size.kind) { case COMP_GT: @@ -1169,22 +1362,46 @@ pred_size (pathname, stat_buf, pred_ptr) } boolean -pred_true (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_samefile (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - return (true); + /* Potential optimisation: because of the loop protection, we always + * know the device of the current directory, hence the device number + * of the file we're currently considering. If -L is not in effect, + * and the device number of the file we're looking for is not the + * same as the device number of the current directory, this + * predicate cannot return true. Hence there would be no need to + * stat the file we're lookingn at. + */ + (void) pathname; + + return stat_buf->st_ino == pred_ptr->args.fileid.ino + && stat_buf->st_dev == pred_ptr->args.fileid.dev; } boolean -pred_type (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_true (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - unsigned long mode = stat_buf->st_mode; - unsigned long type = pred_ptr->args.type; + (void) pathname; + (void) stat_buf; + (void) pred_ptr; + return true; +} + +boolean +pred_type (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) +{ + mode_t mode; + mode_t type = pred_ptr->args.type; + + assert(state.have_type); + assert(state.type != 0); + + (void) pathname; + + if (state.have_stat) + mode = stat_buf->st_mode; + else + mode = state.type; #ifndef S_IFMT /* POSIX system; check `mode' the slow way. */ @@ -1200,6 +1417,9 @@ pred_type (pathname, stat_buf, pred_ptr) #endif #ifdef S_IFSOCK || (S_ISSOCK (mode) && type == S_IFSOCK) +#endif +#ifdef S_IFDOOR + || (S_ISDOOR (mode) && type == S_IFDOOR) #endif ) #else /* S_IFMT */ @@ -1212,11 +1432,9 @@ pred_type (pathname, stat_buf, pred_ptr) } boolean -pred_uid (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_uid (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) pathname; switch (pred_ptr->args.info.kind) { case COMP_GT: @@ -1236,39 +1454,19 @@ pred_uid (pathname, stat_buf, pred_ptr) } boolean -pred_used (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_used (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { time_t delta; + (void) pathname; delta = stat_buf->st_atime - stat_buf->st_ctime; /* Use difftime? */ - switch (pred_ptr->args.info.kind) - { - case COMP_GT: - if (delta > (time_t) pred_ptr->args.info.l_val) - return (true); - break; - case COMP_LT: - if (delta < (time_t) pred_ptr->args.info.l_val) - return (true); - break; - case COMP_EQ: - if ((delta >= (time_t) pred_ptr->args.info.l_val) - && (delta < (time_t) pred_ptr->args.info.l_val + DAYSECS)) - return (true); - break; - } - return (false); + return pred_timewindow(delta, pred_ptr, DAYSECS); } boolean -pred_user (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_user (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { + (void) pathname; if (pred_ptr->args.uid == stat_buf->st_uid) return (true); else @@ -1276,24 +1474,39 @@ pred_user (pathname, stat_buf, pred_ptr) } boolean -pred_xtype (pathname, stat_buf, pred_ptr) - char *pathname; - struct stat *stat_buf; - struct predicate *pred_ptr; +pred_xtype (char *pathname, struct stat *stat_buf, struct predicate *pred_ptr) { - struct stat sbuf; - int (*ystat) (); + struct stat sbuf; /* local copy, not stat_buf because we're using a different stat method */ + int (*ystat) (const char*, struct stat *p); - ystat = xstat == lstat ? stat : lstat; - if ((*ystat) (rel_pathname, &sbuf) != 0) + /* If we would normally stat the link itself, stat the target instead. + * If we would normally follow the link, stat the link itself instead. + */ + if (following_links()) + ystat = optionp_stat; + else + ystat = optionl_stat; + + if ((*ystat) (state.rel_pathname, &sbuf) != 0) { - if (ystat == stat && errno == ENOENT) - /* Mimic behavior of ls -lL. */ - return (pred_type (pathname, stat_buf, pred_ptr)); - error (0, errno, "%s", pathname); - exit_status = 1; - return (false); + if (following_links() && errno == ENOENT) + { + /* If we failed to follow the symlink, + * fall back on looking at the symlink itself. + */ + /* Mimic behavior of ls -lL. */ + return (pred_type (pathname, stat_buf, pred_ptr)); + } + else + { + error (0, errno, "%s", pathname); + state.exit_status = 1; + } + return false; } + /* Now that we have our stat() information, query it in the same + * way that -type does. + */ return (pred_type (pathname, &sbuf, pred_ptr)); } @@ -1315,21 +1528,46 @@ pred_xtype (pathname, stat_buf, pred_ptr) zero, and the exit arg (status high) is 0. Otherwise return false, possibly printing an error message. */ -static boolean -launch (pred_ptr) - struct predicate *pred_ptr; + +static void +prep_child_for_exec (boolean close_stdin) { - int status; - pid_t wait_ret, child_pid; - struct exec_val *execp; /* Pointer for efficiency. */ + if (close_stdin) + { + const char inputfile[] = "/dev/null"; + /* fprintf(stderr, "attaching stdin to /dev/null\n"); */ + + close(0); + if (open(inputfile, O_RDONLY) < 0) + { + /* This is not entirely fatal, since + * executing the child with a closed + * stdin is almost as good as executing it + * with its stdin attached to /dev/null. + */ + error (0, errno, "%s", inputfile); + } + } +} + + + +int +launch (const struct buildcmd_control *ctl, + struct buildcmd_state *buildstate) +{ + int wait_status; + pid_t child_pid; static int first_time = 1; - - execp = &pred_ptr->args.exec_vec; - + const struct exec_val *execp = buildstate->usercontext; + + /* Null terminate the arg list. */ + bc_push_arg (ctl, buildstate, (char *) NULL, 0, NULL, 0, false); + /* Make sure output of command doesn't get mixed with find output. */ fflush (stdout); fflush (stderr); - + /* Make sure to listen for the kids. */ if (first_time) { @@ -1339,83 +1577,137 @@ launch (pred_ptr) child_pid = fork (); if (child_pid == -1) - error (1, errno, "cannot fork"); + error (1, errno, _("cannot fork")); if (child_pid == 0) { /* We be the child. */ -#ifndef HAVE_FCHDIR - if (chdir (starting_dir) < 0) + prep_child_for_exec(execp->close_stdin); + + /* For -exec and -ok, change directory back to the starting directory. + * for -execdir and -okdir, stay in the directory we are searching + * (the latter is more secure). + */ + if (!execp->use_current_dir) { - error (0, errno, "%s", starting_dir); - _exit (1); + /* Even if DEBUG_STAT is set, don't announce our change of + * directory, since we're not going to emit a subsequent + * announcement of a call to stat() anyway, as we're about + * to exec something. + */ + if (starting_desc < 0 + ? chdir (starting_dir) != 0 + : fchdir (starting_desc) != 0) + { + error (0, errno, "%s", starting_dir); + _exit (1); + } } -#else - if (fchdir (starting_desc) < 0) - { - error (0, errno, "cannot return to starting directory"); - _exit (1); - } -#endif - execvp (execp->vec[0], execp->vec); - error (0, errno, "%s", execp->vec[0]); + + execvp (buildstate->cmd_argv[0], buildstate->cmd_argv); + error (0, errno, "%s", buildstate->cmd_argv[0]); _exit (1); } - wait_ret = wait (&status); - if (wait_ret == -1) + + /* In parent; set up for next time. */ + bc_clear_args(ctl, buildstate); + + + while (waitpid (child_pid, &wait_status, 0) == (pid_t) -1) { - error (0, errno, "error waiting for %s", execp->vec[0]); - exit_status = 1; - return (false); + if (errno != EINTR) + { + error (0, errno, _("error waiting for %s"), buildstate->cmd_argv[0]); + state.exit_status = 1; + return 0; /* FAIL */ + } } - if (wait_ret != child_pid) + + if (WIFSIGNALED (wait_status)) { - error (0, 0, "wait got pid %d, expected pid %d", wait_ret, child_pid); - exit_status = 1; - return (false); + error (0, 0, _("%s terminated by signal %d"), + buildstate->cmd_argv[0], WTERMSIG (wait_status)); + + if (execp->multiple) + { + /* -exec \; just returns false if the invoked command fails. + * -exec {} + returns true if the invoked command fails, but + * sets the program exit status. + */ + state.exit_status = 1; + } + + return 1; /* OK */ } - if (WIFSTOPPED (status)) + + if (0 == WEXITSTATUS (wait_status)) { - error (0, 0, "%s stopped by signal %d", - execp->vec[0], WSTOPSIG (status)); - exit_status = 1; - return (false); + return 1; /* OK */ } - if (WIFSIGNALED (status)) + else { - error (0, 0, "%s terminated by signal %d", - execp->vec[0], WTERMSIG (status)); - exit_status = 1; - return (false); + if (execp->multiple) + { + /* -exec \; just returns false if the invoked command fails. + * -exec {} + returns true if the invoked command fails, but + * sets the program exit status. + */ + state.exit_status = 1; + } + return 0; /* FAIL */ } - return (!WEXITSTATUS (status)); + } + /* Return a static string formatting the time WHEN according to the strftime format character KIND. */ static char * -format_date (when, kind) - time_t when; - int kind; +format_date (time_t when, int kind) { - static char fmt[3]; - static char buf[64]; /* More than enough space. */ + static char buf[MAX (LONGEST_HUMAN_READABLE + 2, 64)]; + struct tm *tm; + char fmt[6]; - if (kind == '@') + fmt[0] = '%'; + fmt[1] = kind; + fmt[2] = '\0'; + if (kind == '+') + strcpy (fmt, "%F+%T"); + + if (kind != '@' + && (tm = localtime (&when)) + && strftime (buf, sizeof buf, fmt, tm)) + return buf; + else { - sprintf (buf, "%ld", when); - return (buf); + uintmax_t w = when; + char *p = human_readable (when < 0 ? -w : w, buf + 1, + human_ceiling, 1, 1); + if (when < 0) + *--p = '-'; + return p; + } +} + +static char * +ctime_format (time_t when) +{ + char *r = ctime (&when); + if (!r) + { + /* The time cannot be represented as a struct tm. + Output it as an integer. */ + return format_date (when, '@'); } else { - fmt[0] = '%'; - fmt[1] = kind; - fmt[2] = '\0'; - if (strftime (buf, sizeof (buf), fmt, localtime (&when))) - return (buf); + /* Remove the trailing newline from the ctime output, + being careful not to assume that the output is fixed-width. */ + *strchr (r, '\n') = '\0'; + return r; } - return ""; } #ifdef DEBUG @@ -1462,27 +1754,45 @@ prec_name (prec) INDENT is the number of levels to indent the left margin. */ void -print_tree (node, indent) - struct predicate *node; - int indent; +print_tree (FILE *fp, struct predicate *node, int indent) { int i; if (node == NULL) return; for (i = 0; i < indent; i++) - printf (" "); - printf ("pred = %s type = %s prec = %s addr = %x\n", + fprintf (fp, " "); + fprintf (fp, "pred = %s type = %s prec = %s addr = %p\n", find_pred_name (node->pred_func), type_name (node->p_type), prec_name (node->p_prec), node); + if (node->need_stat || node->need_type) + { + int comma = 0; + + for (i = 0; i < indent; i++) + fprintf (fp, " "); + + fprintf (fp, "Needs "); + if (node->need_stat) + { + fprintf (fp, "stat"); + comma = 1; + } + if (node->need_type) + { + fprintf (fp, "%stype", comma ? "," : ""); + } + fprintf (fp, "\n"); + } + for (i = 0; i < indent; i++) - printf (" "); - printf ("left:\n"); - print_tree (node->pred_left, indent + 1); + fprintf (fp, " "); + fprintf (fp, "left:\n"); + print_tree (fp, node->pred_left, indent + 1); for (i = 0; i < indent; i++) - printf (" "); - printf ("right:\n"); - print_tree (node->pred_right, indent + 1); + fprintf (fp, " "); + fprintf (fp, "right:\n"); + print_tree (fp, node->pred_right, indent + 1); } /* Copy STR into BUF and trim blanks from the end of BUF. @@ -1508,8 +1818,7 @@ blank_rtrim (str, buf) /* Print out the predicate list starting at NODE. */ void -print_list (node) - struct predicate *node; +print_list (FILE *fp, struct predicate *node) { struct predicate *cur; char name[256]; @@ -1517,9 +1826,126 @@ print_list (node) cur = node; while (cur != NULL) { - printf ("%s ", blank_rtrim (find_pred_name (cur->pred_func), name)); + fprintf (fp, "%s ", blank_rtrim (find_pred_name (cur->pred_func), name)); cur = cur->pred_next; } - printf ("\n"); + fprintf (fp, "\n"); } + + +/* Print out the predicate list starting at NODE. */ + + +static void +print_parenthesised(FILE *fp, struct predicate *node) +{ + int parens = 0; + + if (node) + { + if ( ( (node->pred_func == pred_or) + || (node->pred_func == pred_and) ) + && node->pred_left == NULL) + { + /* We print " or X" as just "X" + * We print " and X" as just "X" + */ + print_parenthesised(fp, node->pred_right); + } + else + { + if (node->pred_left || node->pred_right) + parens = 1; + + if (parens) + fprintf(fp, "%s", " ( "); + print_optlist(fp, node); + if (parens) + fprintf(fp, "%s", " ) "); + } + } +} + +void +print_optlist (FILE *fp, struct predicate *p) +{ + char name[256]; + + if (p) + { + print_parenthesised(fp, p->pred_left); + fprintf (fp, + "%s%s%s ", + p->need_stat ? "[stat called here] " : "", + p->need_type ? "[type needed here] " : "", + blank_rtrim (find_pred_name (p->pred_func), name)); + print_parenthesised(fp, p->pred_right); + } +} + #endif /* DEBUG */ + + +void +pred_sanity_check(const struct predicate *predicates) +{ + const struct predicate *p; + + for (p=predicates; p != NULL; p=p->pred_next) + { + /* All predicates must do something. */ + assert(p->pred_func != NULL); + + /* All predicates must have a parser table entry. */ + assert(p->parser_entry != NULL); + + /* If the parser table tells us that just one predicate function is + * possible, verify that that is still the one that is in effect. + * If the parser has NULL for the predicate function, that means that + * the parse_xxx function fills it in, so we can't check it. + */ + if (p->parser_entry->pred_func) + { + assert(p->parser_entry->pred_func == p->pred_func); + } + + switch (p->parser_entry->type) + { + /* Options all take effect during parsing, so there should + * be no predicate entries corresponding to them. Hence we + * should not see any ARG_OPTION or ARG_POSITIONAL_OPTION + * items. + * + * This is a silly way of coding this test, but it prevents + * a compiler warning (i.e. otherwise it would think that + * there would be case statements missing). + */ + case ARG_OPTION: + case ARG_POSITIONAL_OPTION: + assert(p->parser_entry->type != ARG_OPTION); + assert(p->parser_entry->type != ARG_POSITIONAL_OPTION); + break; + + case ARG_ACTION: + assert(p->side_effects); /* actions have side effects. */ + if (p->pred_func != pred_prune && p->pred_func != pred_quit) + { + /* actions other than -prune and -quit should + * inhibit the default -print + */ + assert(p->no_default_print); + } + break; + + case ARG_PUNCTUATION: + case ARG_TEST: + /* Punctuation and tests should have no side + * effects and not inhibit default print. + */ + assert(!p->no_default_print); + assert(!p->side_effects); + break; + + } + } +} diff --git a/src/bin/findutils/find/tree.c b/src/bin/findutils/find/tree.c index 220924278c..1acd142695 100644 --- a/src/bin/findutils/find/tree.c +++ b/src/bin/findutils/find/tree.c @@ -1,29 +1,41 @@ /* tree.c -- helper functions to build and evaluate the expression tree. - Copyright (C) 1990, 91, 92, 93, 94 Free Software Foundation, Inc. + Copyright (C) 1990, 91, 92, 93, 94, 2000, 2001, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ -#include -#include -#include -#include #include "defs.h" +#include "../gnulib/lib/xalloc.h" -static struct predicate *scan_rest P_((struct predicate **input, struct predicate *head, int prev_prec)); -static void merge_pred P_((struct predicate *beg_list, struct predicate *end_list, struct predicate **last_p)); -static struct predicate *set_new_parent P_((struct predicate *curr, enum predicate_precedence high_prec, struct predicate **prevp)); +#if ENABLE_NLS +# include +# define _(Text) gettext (Text) +#else +# define _(Text) Text +#endif +#ifdef gettext_noop +# define N_(String) gettext_noop (String) +#else +/* See locate.c for explanation as to why not use (String) */ +# define N_(String) String +#endif + +static struct predicate *scan_rest PARAMS((struct predicate **input, + struct predicate *head, + short int prev_prec)); +static void merge_pred PARAMS((struct predicate *beg_list, struct predicate *end_list, struct predicate **last_p)); +static struct predicate *set_new_parent PARAMS((struct predicate *curr, enum predicate_precedence high_prec, struct predicate **prevp)); /* Return a pointer to a tree that represents the expression prior to non-unary operator *INPUT. @@ -45,20 +57,25 @@ static struct predicate *set_new_parent P_((struct predicate *curr, enum predica our caller, so get_expr recurses. */ struct predicate * -get_expr (input, prev_prec) - struct predicate **input; - short prev_prec; +get_expr (struct predicate **input, short int prev_prec) { - struct predicate *next; + struct predicate *next = NULL; if (*input == NULL) - error (1, 0, "invalid expression"); + error (1, 0, _("invalid expression")); + switch ((*input)->p_type) { case NO_TYPE: + error (1, 0, _("invalid expression")); + break; + case BI_OP: + error (1, 0, _("invalid expression; you have used a binary operator with nothing before it.")); + break; + case CLOSE_PAREN: - error (1, 0, "invalid expression"); + error (1, 0, _("invalid expression; you have too many ')'")); break; case PRIMARY_TYPE: @@ -77,12 +94,12 @@ get_expr (input, prev_prec) next = get_expr (input, NO_PREC); if ((*input == NULL) || ((*input)->p_type != CLOSE_PAREN)) - error (1, 0, "invalid expression"); + error (1, 0, _("invalid expression; I was expecting to find a ')' somewhere but did not see one.")); *input = (*input)->pred_next; /* move over close */ break; default: - error (1, 0, "oops -- invalid expression type!"); + error (1, 0, _("oops -- invalid expression type!")); break; } @@ -97,7 +114,7 @@ get_expr (input, prev_prec) { next = scan_rest (input, next, prev_prec); if (next == NULL) - error (1, 0, "invalid expression"); + error (1, 0, _("invalid expression")); } return (next); } @@ -116,10 +133,9 @@ get_expr (input, prev_prec) PREV_PREC is the precedence of the previous predicate element. */ static struct predicate * -scan_rest (input, head, prev_prec) - struct predicate **input; - struct predicate *head; - short prev_prec; +scan_rest (struct predicate **input, + struct predicate *head, + short int prev_prec) { struct predicate *tree; /* The new tree we are building. */ @@ -134,7 +150,10 @@ scan_rest (input, head, prev_prec) case PRIMARY_TYPE: case UNI_OP: case OPEN_PAREN: - error (1, 0, "invalid expression"); + /* I'm not sure how we get here, so it is not obvious what + * sort of mistakes might give rise to this condition. + */ + error (1, 0, _("invalid expression")); break; case BI_OP: @@ -145,14 +164,16 @@ scan_rest (input, head, prev_prec) break; case CLOSE_PAREN: - return (tree); + return tree; default: - error (1, 0, "oops -- invalid expression type!"); + error (1, 0, + _("oops -- invalid expression type (%d)!"), + (int)(*input)->p_type); break; } } - return (tree); + return tree; } /* Optimize the ordering of the predicates in the tree. Rearrange @@ -162,9 +183,12 @@ scan_rest (input, head, prev_prec) predicates (if any) which have "side effects", such as printing. The grouping implements the partial ordering on predicates which those with side effects impose. - * Place -name, -path, and -regex at the front of a group, with - -name and -path ahead of -regex. Predicates that are moved to the - front of a group by definition do not have side effects. + + * Place -name, -iname, -path, -ipath, -regex and -iregex at the front + of a group, with -name, -iname, -path and -ipath ahead of + -regex and -iregex. Predicates which are moved to the front + of a group by definition do not have side effects. Both + -regex and -iregex both use pred_regex. This routine "normalizes" the predicate tree by ensuring that all expression predicates have AND (or OR or COMMA) parent nodes @@ -176,8 +200,7 @@ scan_rest (input, head, prev_prec) Return true if the tree contains side effects, false if not. */ boolean -opt_expr (eval_treep) - struct predicate **eval_treep; +opt_expr (struct predicate **eval_treep) { /* List of -name and -path predicates to move. */ struct predicate *name_list = NULL; @@ -188,7 +211,7 @@ opt_expr (eval_treep) struct predicate *curr; struct predicate **prevp; /* Address of `curr' node. */ struct predicate **last_sidep; /* Last predicate with side effects. */ - PFB pred_func; + PRED_FUNC pred_func; enum predicate_type p_type; boolean has_side_effects = false; /* Return value. */ enum predicate_precedence prev_prec, /* precedence of last BI_OP in branch */ @@ -217,12 +240,13 @@ opt_expr (eval_treep) #ifdef DEBUG /* Normalized tree. */ - printf ("Normalized Eval Tree:\n"); - print_tree (*eval_treep, 0); + fprintf (stderr, "Normalized Eval Tree:\n"); + print_tree (stderr, *eval_treep, 0); #endif /* Rearrange the predicates. */ prevp = eval_treep; + biop_prec = NO_PREC; /* not COMMA_PREC */ if ((*prevp) && (*prevp)->p_type == BI_OP) biop_prec = (*prevp)->p_prec; while ((curr = *prevp) != NULL) @@ -237,8 +261,6 @@ opt_expr (eval_treep) { if (curr->p_prec != biop_prec) curr = set_new_parent(curr, biop_prec, prevp); - else - biop_prec = curr->p_prec; } /* See which predicate type we have. */ @@ -249,9 +271,15 @@ opt_expr (eval_treep) { case NO_TYPE: case PRIMARY_TYPE: + /* Don't rearrange the arguments of the comma operator, it is + not commutative. */ + if (biop_prec == COMMA_PREC) + break; + /* If it's one of our special primaries, move it to the front of the list for that primary. */ - if (pred_func == pred_name || pred_func == pred_path) + if (pred_func == pred_name || pred_func == pred_path || + pred_func == pred_iname || pred_func == pred_ipath) { *prevp = curr->pred_left; curr->pred_left = name_list; @@ -293,7 +321,7 @@ opt_expr (eval_treep) all of the user's parentheses. */ default: - error (1, 0, "oops -- invalid expression type!"); + error (1, 0, _("oops -- invalid expression type!")); break; } @@ -334,10 +362,7 @@ opt_expr (eval_treep) HIGH_PREC. */ static struct predicate * -set_new_parent (curr, high_prec, prevp) - struct predicate *curr; - enum predicate_precedence high_prec; - struct predicate **prevp; +set_new_parent (struct predicate *curr, enum predicate_precedence high_prec, struct predicate **prevp) { struct predicate *new_parent; @@ -345,6 +370,7 @@ set_new_parent (curr, high_prec, prevp) new_parent->p_type = BI_OP; new_parent->p_prec = high_prec; new_parent->need_stat = false; + new_parent->need_type = false; switch (high_prec) { @@ -362,6 +388,7 @@ set_new_parent (curr, high_prec, prevp) } new_parent->side_effects = false; + new_parent->no_default_print = false; new_parent->args.str = NULL; new_parent->pred_next = NULL; @@ -382,8 +409,7 @@ set_new_parent (curr, high_prec, prevp) into the tree at LAST_P. */ static void -merge_pred (beg_list, end_list, last_p) - struct predicate *beg_list, *end_list, **last_p; +merge_pred (struct predicate *beg_list, struct predicate *end_list, struct predicate **last_p) { end_list->pred_left = *last_p; *last_p = beg_list; @@ -400,8 +426,7 @@ merge_pred (beg_list, end_list, last_p) in TREE requires a stat, false if not. */ boolean -mark_stat (tree) - struct predicate *tree; +mark_stat (struct predicate *tree) { /* The tree is executed in-order, so walk this way (apologies to Aerosmith) to find the first predicate for which the stat is needed. */ @@ -427,7 +452,44 @@ mark_stat (tree) return (false); default: - error (1, 0, "oops -- invalid expression type!"); + error (1, 0, _("oops -- invalid expression type in mark_stat!")); return (false); } } + +/* Find the first node in expression tree TREE that we will + need to know the file type, if any. Operates in the same + was as mark_stat(). +*/ +boolean +mark_type (struct predicate *tree) +{ + /* The tree is executed in-order, so walk this way (apologies to Aerosmith) + to find the first predicate for which the type information is needed. */ + switch (tree->p_type) + { + case NO_TYPE: + case PRIMARY_TYPE: + return tree->need_type; + + case UNI_OP: + if (mark_type (tree->pred_right)) + tree->need_type = true; + return false; + + case BI_OP: + /* ANDs and ORs are linked along ->left ending in NULL. */ + if (tree->pred_left != NULL) + mark_type (tree->pred_left); + + if (mark_type (tree->pred_right)) + tree->need_type = true; + + return false; + + default: + error (1, 0, _("oops -- invalid expression type in mark_type!")); + return (false); + } +} + diff --git a/src/bin/findutils/find/util.c b/src/bin/findutils/find/util.c index 95ce57e08e..45188f23d1 100644 --- a/src/bin/findutils/find/util.c +++ b/src/bin/findutils/find/util.c @@ -1,43 +1,38 @@ /* util.c -- functions for initializing new tree elements, and other things. - Copyright (C) 1990, 91, 92, 93, 94 Free Software Foundation, Inc. + Copyright (C) 1990, 91, 92, 93, 94, 2000, 2001, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ -#include -#include -#include -#include #include "defs.h" - -/* Return the last component of pathname FNAME, with leading slashes - compressed into one slash. */ +#include "xalloc.h" -char * -basename (fname) - char *fname; -{ - char *p; +#if ENABLE_NLS +# include +# define _(Text) gettext (Text) +#else +# define _(Text) Text +#endif +#ifdef gettext_noop +# define N_(String) gettext_noop (String) +#else +/* See locate.c for explanation as to why not use (String) */ +# define N_(String) String +#endif + +#include - /* For "/", "//", etc., return "/". */ - for (p = fname; *p == '/'; ++p) - /* Do nothing. */ ; - if (*p == '\0') - return p - 1; - p = strrchr (fname, '/'); - return (p == NULL ? fname : p + 1); -} /* Return a pointer to a new predicate structure, which has been linked in as the last one in the predicates list. @@ -48,10 +43,15 @@ basename (fname) Set all cells in the new structure to the default values. */ struct predicate * -get_new_pred () +get_new_pred (const struct parser_table *entry) { register struct predicate *new_pred; + (void) entry; + /* Options should not be turned into predicates. */ + assert(entry->type != ARG_OPTION); + assert(entry->type != ARG_POSITIONAL_OPTION); + if (predicates == NULL) { predicates = (struct predicate *) @@ -64,6 +64,7 @@ get_new_pred () last_pred->pred_next = new_pred; last_pred = new_pred; } + last_pred->parser_entry = entry; last_pred->pred_func = NULL; #ifdef DEBUG last_pred->p_name = NULL; @@ -71,7 +72,9 @@ get_new_pred () last_pred->p_type = NO_TYPE; last_pred->p_prec = NO_PREC; last_pred->side_effects = false; + last_pred->no_default_print = false; last_pred->need_stat = true; + last_pred->need_type = true; last_pred->args.str = NULL; last_pred->pred_next = NULL; last_pred->pred_left = NULL; @@ -84,20 +87,29 @@ get_new_pred () predicate is an operator. If it isn't, the AND operator is inserted. */ struct predicate * -get_new_pred_chk_op () +get_new_pred_chk_op (const struct parser_table *entry) { struct predicate *new_pred; + static const struct parser_table *entry_and = NULL; + + /* Locate the entry in the parser table for the "and" operator */ + if (NULL == entry_and) + entry_and = find_parser("and"); + + /* Check that it's actually there. If not, that is a bug.*/ + assert(entry_and != NULL); if (last_pred) switch (last_pred->p_type) { case NO_TYPE: - error (1, 0, "oops -- invalid default insertion of and!"); + error (1, 0, _("oops -- invalid default insertion of and!")); break; case PRIMARY_TYPE: case CLOSE_PAREN: - new_pred = get_new_pred (); + /* We need to interpose the and operator. */ + new_pred = get_new_pred (entry_and); new_pred->pred_func = pred_and; #ifdef DEBUG new_pred->p_name = find_pred_name (pred_and); @@ -105,15 +117,22 @@ get_new_pred_chk_op () new_pred->p_type = BI_OP; new_pred->p_prec = AND_PREC; new_pred->need_stat = false; + new_pred->need_type = false; new_pred->args.str = NULL; + new_pred->side_effects = false; + new_pred->no_default_print = false; + break; default: break; } - return (get_new_pred ()); + + new_pred = get_new_pred (entry); + new_pred->parser_entry = entry; + return new_pred; } -/* Add a primary of predicate type PRED_FUNC to the predicate input list. +/* Add a primary of predicate type PRED_FUNC (described by ENTRY) to the predicate input list. Return a pointer to the predicate node just inserted. @@ -130,29 +149,51 @@ get_new_pred_chk_op () operator. */ struct predicate * -insert_primary (pred_func) - boolean (*pred_func) (); +insert_primary_withpred (const struct parser_table *entry, PRED_FUNC pred_func) { struct predicate *new_pred; - new_pred = get_new_pred_chk_op (); + new_pred = get_new_pred_chk_op (entry); new_pred->pred_func = pred_func; #ifdef DEBUG - new_pred->p_name = find_pred_name (pred_func); + new_pred->p_name = entry->parser_name; #endif /* DEBUG */ new_pred->args.str = NULL; new_pred->p_type = PRIMARY_TYPE; new_pred->p_prec = NO_PREC; - return (new_pred); + return new_pred; } + +/* Add a primary described by ENTRY to the predicate input list. + + Return a pointer to the predicate node just inserted. + + Fills in the following cells of the new predicate node: + + pred_func PRED_FUNC + args(.str) NULL + p_type PRIMARY_TYPE + p_prec NO_PREC + + Other cells that need to be filled in are defaulted by + get_new_pred_chk_op, which is used to insure that the prior node is + either not there at all (we are the very first node) or is an + operator. */ +struct predicate * +insert_primary (const struct parser_table *entry) +{ + assert(entry->pred_func != NULL); + return insert_primary_withpred(entry, entry->pred_func); +} + + void -usage (msg) - char *msg; +usage (char *msg) { if (msg) fprintf (stderr, "%s: %s\n", program_name, msg); - fprintf (stderr, "\ -Usage: %s [path...] [expression]\n", program_name); + fprintf (stderr, _("\ +Usage: %s [-H] [-L] [-P] [path...] [expression]\n"), program_name); exit (1); } diff --git a/src/bin/findutils/find/version.c b/src/bin/findutils/find/version.c index 460883ff22..c833c5bf5a 100644 --- a/src/bin/findutils/find/version.c +++ b/src/bin/findutils/find/version.c @@ -1 +1,3 @@ -char *version_string = "4.1"; +#include +char *version_string = VERSION; + diff --git a/src/bin/findutils/findutils.rdef b/src/bin/findutils/findutils.rdef index 613d1262eb..db94cdabc6 100644 --- a/src/bin/findutils/findutils.rdef +++ b/src/bin/findutils/findutils.rdef @@ -1,11 +1,11 @@ resource app_version { major = 4, - middle = 1, - minor = 0, + middle = 2, + minor = 33, variety = 5, internal = 0, - short_info = "4.1", - long_info = "4.1 ©1994 The Free Software Foundation" + short_info = "4.2.33", + long_info = "4.2.33 ©2008 The Free Software Foundation" }; diff --git a/src/bin/findutils/gnulib/Jamfile b/src/bin/findutils/gnulib/Jamfile new file mode 100644 index 0000000000..2a96672c77 --- /dev/null +++ b/src/bin/findutils/gnulib/Jamfile @@ -0,0 +1,3 @@ +SubDir HAIKU_TOP src bin findutils gnulib ; + +SubInclude HAIKU_TOP src bin findutils gnulib lib ; diff --git a/src/bin/findutils/gnulib/lib/Jamfile b/src/bin/findutils/gnulib/lib/Jamfile new file mode 100644 index 0000000000..57b6a7c673 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/Jamfile @@ -0,0 +1,58 @@ +SubDir HAIKU_TOP src bin findutils gnulib lib ; + +SubDirSysHdrs [ FDirName $(SUBDIR) ] ; +SubDirSysHdrs [ FDirName $(SUBDIR) $(DOTDOT) $(DOTDOT) ] ; + +# filter warnings we don't want here +TARGET_WARNING_CCFLAGS = [ FFilter $(TARGET_WARNING_CCFLAGS) + : -Wall -Wmissing-prototypes -Wsign-compare ] ; + +# set some additional defines +{ + SubDirCcFlags -DHAVE_CONFIG_H ; +} + + +StaticLibrary gnulibfindutils.a : + areadlink-with-size.c + argmatch.c + basename.c + canonicalize.c + closein.c + closeout.c + close-stream.c + dirname.c + dup-safer.c + error.c + exitfail.c + filemode.c + file-set.c + fnmatch.c + fopen-safer.c + fpending.c + freadahead.c + getcwd.c + hash.c + hash-pjw.c + hash-triple.c + human.c + idcache.c + localcharset.c + modechange.c + mountlist.c + quote.c + quotearg.c + regex.c + same.c + stripslash.c + strndup.c + xalloc-die.c + xgetcwd.c + xmalloc.c + xstrndup.c + xstrtol-error.c + xstrtoumax.c + yesno.c +; + +#SEARCH on [ FGristFiles version.c ] = [ FDirName $(SUBDIR) $(DOTDOT) find ] ; diff --git a/src/bin/findutils/lib/alloca.c b/src/bin/findutils/gnulib/lib/alloca.c similarity index 84% rename from src/bin/findutils/lib/alloca.c rename to src/bin/findutils/gnulib/lib/alloca.c index 7020f32c88..ff1cb7e9a6 100644 --- a/src/bin/findutils/lib/alloca.c +++ b/src/bin/findutils/gnulib/lib/alloca.c @@ -21,12 +21,22 @@ allocating any. It is a good idea to use alloca(0) in your main control loop, etc. to force garbage collection. */ -#ifdef HAVE_CONFIG_H #include -#endif + +#include + +#include +#include #ifdef emacs -#include "blockinput.h" +# include "lisp.h" +# include "blockinput.h" +# ifdef EMACS_FREE +# undef free +# define free EMACS_FREE +# endif +#else +# define memory_full() abort () #endif /* If compiling with GCC 2, this file's not needed. */ @@ -34,54 +44,33 @@ /* If someone has defined alloca as a macro, there must be some other way alloca is supposed to work. */ -#ifndef alloca +# ifndef alloca -#ifdef emacs -#ifdef static +# ifdef emacs +# ifdef static /* actually, only want this if static is defined as "" -- this is for usg, in which emacs must undefine static in order to make unexec workable */ -#ifndef STACK_DIRECTION +# ifndef STACK_DIRECTION you lose -- must know STACK_DIRECTION at compile-time -#endif /* STACK_DIRECTION undefined */ -#endif /* static */ -#endif /* emacs */ +/* Using #error here is not wise since this file should work for + old and obscure compilers. */ +# endif /* STACK_DIRECTION undefined */ +# endif /* static */ +# endif /* emacs */ /* If your stack is a linked list of frames, you have to provide an "address metric" ADDRESS_FUNCTION macro. */ -#if defined (CRAY) && defined (CRAY_STACKSEG_END) +# if defined (CRAY) && defined (CRAY_STACKSEG_END) long i00afunc (); -#define ADDRESS_FUNCTION(arg) (char *) i00afunc (&(arg)) -#else -#define ADDRESS_FUNCTION(arg) &(arg) -#endif - -#if __STDC__ -typedef void *pointer; -#else -typedef char *pointer; -#endif - -#define NULL 0 - -/* Different portions of Emacs need to call different versions of - malloc. The Emacs executable needs alloca to call xmalloc, because - ordinary malloc isn't protected from input signals. On the other - hand, the utilities in lib-src need alloca to call malloc; some of - them are very simple, and don't have an xmalloc routine. - - Non-Emacs programs expect this to call use xmalloc. - - Callers below should use malloc. */ - -#ifndef emacs -#define malloc xmalloc -#endif -extern pointer malloc (); +# define ADDRESS_FUNCTION(arg) (char *) i00afunc (&(arg)) +# else +# define ADDRESS_FUNCTION(arg) &(arg) +# endif /* Define STACK_DIRECTION if you know the direction of stack growth for your system; otherwise it will be automatically @@ -91,21 +80,21 @@ extern pointer malloc (); STACK_DIRECTION < 0 => grows toward lower addresses STACK_DIRECTION = 0 => direction of growth unknown */ -#ifndef STACK_DIRECTION -#define STACK_DIRECTION 0 /* Direction unknown. */ -#endif +# ifndef STACK_DIRECTION +# define STACK_DIRECTION 0 /* Direction unknown. */ +# endif -#if STACK_DIRECTION != 0 +# if STACK_DIRECTION != 0 -#define STACK_DIR STACK_DIRECTION /* Known at compile-time. */ +# define STACK_DIR STACK_DIRECTION /* Known at compile-time. */ -#else /* STACK_DIRECTION == 0; need run-time code. */ +# else /* STACK_DIRECTION == 0; need run-time code. */ static int stack_dir; /* 1 or -1 once known. */ -#define STACK_DIR stack_dir +# define STACK_DIR stack_dir static void -find_stack_direction () +find_stack_direction (void) { static char *addr = NULL; /* Address of first `dummy', once known. */ auto char dummy; /* To get stack address. */ @@ -126,7 +115,7 @@ find_stack_direction () } } -#endif /* STACK_DIRECTION == 0 */ +# endif /* STACK_DIRECTION == 0 */ /* An "alloca header" is used to: (a) chain together all alloca'ed blocks; @@ -135,9 +124,9 @@ find_stack_direction () It is very important that sizeof(header) agree with malloc alignment chunk size. The following default should work okay. */ -#ifndef ALIGN_SIZE -#define ALIGN_SIZE sizeof(double) -#endif +# ifndef ALIGN_SIZE +# define ALIGN_SIZE sizeof(double) +# endif typedef union hdr { @@ -158,27 +147,26 @@ static header *last_alloca_header = NULL; /* -> last alloca header. */ caller, but that method cannot be made to work for some implementations of C, for example under Gould's UTX/32. */ -pointer -alloca (size) - unsigned size; +void * +alloca (size_t size) { auto char probe; /* Probes stack depth: */ register char *depth = ADDRESS_FUNCTION (probe); -#if STACK_DIRECTION == 0 +# if STACK_DIRECTION == 0 if (STACK_DIR == 0) /* Unknown growth direction. */ find_stack_direction (); -#endif +# endif /* Reclaim garbage, defined as all alloca'd storage that - was allocated from deeper in the stack than currently. */ + was allocated from deeper in the stack than currently. */ { register header *hp; /* Traverses linked list. */ -#ifdef emacs +# ifdef emacs BLOCK_INPUT; -#endif +# endif for (hp = last_alloca_header; hp != NULL;) if ((STACK_DIR > 0 && hp->h.deep > depth) @@ -186,7 +174,7 @@ alloca (size) { register header *np = hp->h.next; - free ((pointer) hp); /* Collect garbage. */ + free (hp); /* Collect garbage. */ hp = np; /* -> next header. */ } @@ -195,9 +183,9 @@ alloca (size) last_alloca_header = hp; /* -> last valid storage. */ -#ifdef emacs +# ifdef emacs UNBLOCK_INPUT; -#endif +# endif } if (size == 0) @@ -206,29 +194,38 @@ alloca (size) /* Allocate combined header + user data storage. */ { - register pointer new = malloc (sizeof (header) + size); /* Address of header. */ + register header *new; - ((header *) new)->h.next = last_alloca_header; - ((header *) new)->h.deep = depth; + size_t combined_size = sizeof (header) + size; + if (combined_size < sizeof (header)) + memory_full (); - last_alloca_header = (header *) new; + new = malloc (combined_size); + + if (! new) + memory_full (); + + new->h.next = last_alloca_header; + new->h.deep = depth; + + last_alloca_header = new; /* User storage begins just after header. */ - return (pointer) ((char *) new + sizeof (header)); + return (void *) (new + 1); } } -#if defined (CRAY) && defined (CRAY_STACKSEG_END) +# if defined (CRAY) && defined (CRAY_STACKSEG_END) -#ifdef DEBUG_I00AFUNC -#include -#endif +# ifdef DEBUG_I00AFUNC +# include +# endif -#ifndef CRAY_STACK -#define CRAY_STACK -#ifndef CRAY2 +# ifndef CRAY_STACK +# define CRAY_STACK +# ifndef CRAY2 /* Stack structures for CRAY-1, CRAY X-MP, and CRAY Y-MP */ struct stack_control_header { @@ -280,7 +277,7 @@ struct stack_segment_linkage long sss7; }; -#else /* CRAY2 */ +# else /* CRAY2 */ /* The following structure defines the vector of words returned by the STKSTAT library routine. */ struct stk_stat @@ -333,12 +330,12 @@ struct stk_trailer long unknown14; }; -#endif /* CRAY2 */ -#endif /* not CRAY_STACK */ +# endif /* CRAY2 */ +# endif /* not CRAY_STACK */ -#ifdef CRAY2 +# ifdef CRAY2 /* Determine a "stack measure" for an arbitrary ADDRESS. - I doubt that "lint" will like this much. */ + I doubt that "lint" will like this much. */ static long i00afunc (long *address) @@ -407,7 +404,7 @@ i00afunc (long *address) return (result); } -#else /* not CRAY2 */ +# else /* not CRAY2 */ /* Stack address function for a CRAY-1, CRAY X-MP, or CRAY Y-MP. Determine the number of the cell within the stack, given the address of the cell. The purpose of this @@ -452,9 +449,9 @@ i00afunc (long address) while (!(this_segment <= address && address <= stkl)) { -#ifdef DEBUG_I00AFUNC +# ifdef DEBUG_I00AFUNC fprintf (stderr, "%011o %011o %011o\n", this_segment, address, stkl); -#endif +# endif if (pseg == 0) break; stkl = stkl - pseg; @@ -473,9 +470,9 @@ i00afunc (long address) while (pseg != 0) { -#ifdef DEBUG_I00AFUNC +# ifdef DEBUG_I00AFUNC fprintf (stderr, "%011o %011o\n", pseg, size); -#endif +# endif stkl = stkl - pseg; ssptr = (struct stack_segment_linkage *) stkl; size = ssptr->sssize; @@ -485,8 +482,8 @@ i00afunc (long address) return (result); } -#endif /* not CRAY2 */ -#endif /* CRAY */ +# endif /* not CRAY2 */ +# endif /* CRAY */ -#endif /* no alloca */ -#endif /* not GCC version 2 */ +# endif /* no alloca */ +#endif /* not GCC version 3 */ diff --git a/src/bin/findutils/gnulib/lib/alloca.h b/src/bin/findutils/gnulib/lib/alloca.h new file mode 100644 index 0000000000..64f320bf18 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/alloca.h @@ -0,0 +1,55 @@ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +/* Memory allocation on the stack. + + Copyright (C) 1995, 1999, 2001-2004, 2006-2007 Free Software + Foundation, Inc. + + This program is free software; you can redistribute it and/or modify it + under the terms of the GNU General Public License as published + by the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + USA. */ + +/* Avoid using the symbol _ALLOCA_H here, as Bison assumes _ALLOCA_H + means there is a real alloca function. */ +#ifndef _GL_ALLOCA_H +#define _GL_ALLOCA_H + +/* alloca (N) returns a pointer to N bytes of memory + allocated on the stack, which will last until the function returns. + Use of alloca should be avoided: + - inside arguments of function calls - undefined behaviour, + - in inline functions - the allocation may actually last until the + calling function returns, + - for huge N (say, N >= 65536) - you never know how large (or small) + the stack is, and when the stack cannot fulfill the memory allocation + request, the program just crashes. + */ + +#ifndef alloca +# ifdef __GNUC__ +# define alloca __builtin_alloca +# elif defined _AIX +# define alloca __alloca +# elif defined _MSC_VER +# include +# define alloca _alloca +# else +# include +# ifdef __cplusplus +extern "C" +# endif +void *alloca (size_t); +# endif +#endif + +#endif /* _GL_ALLOCA_H */ diff --git a/src/bin/findutils/gnulib/lib/alloca.in.h b/src/bin/findutils/gnulib/lib/alloca.in.h new file mode 100644 index 0000000000..82782884ea --- /dev/null +++ b/src/bin/findutils/gnulib/lib/alloca.in.h @@ -0,0 +1,54 @@ +/* Memory allocation on the stack. + + Copyright (C) 1995, 1999, 2001-2004, 2006-2007 Free Software + Foundation, Inc. + + This program is free software; you can redistribute it and/or modify it + under the terms of the GNU General Public License as published + by the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + USA. */ + +/* Avoid using the symbol _ALLOCA_H here, as Bison assumes _ALLOCA_H + means there is a real alloca function. */ +#ifndef _GL_ALLOCA_H +#define _GL_ALLOCA_H + +/* alloca (N) returns a pointer to N bytes of memory + allocated on the stack, which will last until the function returns. + Use of alloca should be avoided: + - inside arguments of function calls - undefined behaviour, + - in inline functions - the allocation may actually last until the + calling function returns, + - for huge N (say, N >= 65536) - you never know how large (or small) + the stack is, and when the stack cannot fulfill the memory allocation + request, the program just crashes. + */ + +#ifndef alloca +# ifdef __GNUC__ +# define alloca __builtin_alloca +# elif defined _AIX +# define alloca __alloca +# elif defined _MSC_VER +# include +# define alloca _alloca +# else +# include +# ifdef __cplusplus +extern "C" +# endif +void *alloca (size_t); +# endif +#endif + +#endif /* _GL_ALLOCA_H */ diff --git a/src/bin/findutils/gnulib/lib/areadlink-with-size.c b/src/bin/findutils/gnulib/lib/areadlink-with-size.c new file mode 100644 index 0000000000..d0bcb70ad5 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/areadlink-with-size.c @@ -0,0 +1,108 @@ +/* readlink wrapper to return the link name in malloc'd storage. + Unlike xreadlink and xreadlink_with_size, don't ever call exit. + + Copyright (C) 2001, 2003-2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Jim Meyering */ + +#include + +#include "areadlink.h" + +#include +#include +#include +#include +#include +#include + +#ifndef SIZE_MAX +# define SIZE_MAX ((size_t) -1) +#endif +#ifndef SSIZE_MAX +# define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2)) +#endif + +/* SYMLINK_MAX is used only for an initial memory-allocation sanity + check, so it's OK to guess too small on hosts where there is no + arbitrary limit to symbolic link length. */ +#ifndef SYMLINK_MAX +# define SYMLINK_MAX 1024 +#endif + +#define MAXSIZE (SIZE_MAX < SSIZE_MAX ? SIZE_MAX : SSIZE_MAX) + +/* Call readlink to get the symbolic link value of FILE. + SIZE is a hint as to how long the link is expected to be; + typically it is taken from st_size. It need not be correct. + Return a pointer to that NUL-terminated string in malloc'd storage. + If readlink fails, malloc fails, or if the link value is longer + than SSIZE_MAX, return NULL (caller may use errno to diagnose). */ + +char * +areadlink_with_size (char const *file, size_t size) +{ + /* Some buggy file systems report garbage in st_size. Defend + against them by ignoring outlandish st_size values in the initial + memory allocation. */ + size_t symlink_max = SYMLINK_MAX; + size_t INITIAL_LIMIT_BOUND = 8 * 1024; + size_t initial_limit = (symlink_max < INITIAL_LIMIT_BOUND + ? symlink_max + 1 + : INITIAL_LIMIT_BOUND); + + /* The initial buffer size for the link value. */ + size_t buf_size = size < initial_limit ? size + 1 : initial_limit; + + while (1) + { + ssize_t r; + size_t link_length; + char *buffer = malloc (buf_size); + + if (buffer == NULL) + return NULL; + r = readlink (file, buffer, buf_size); + link_length = r; + + /* On AIX 5L v5.3 and HP-UX 11i v2 04/09, readlink returns -1 + with errno == ERANGE if the buffer is too small. */ + if (r < 0 && errno != ERANGE) + { + int saved_errno = errno; + free (buffer); + errno = saved_errno; + return NULL; + } + + if (link_length < buf_size) + { + buffer[link_length] = 0; + return buffer; + } + + free (buffer); + if (buf_size <= MAXSIZE / 2) + buf_size *= 2; + else if (buf_size < MAXSIZE) + buf_size = MAXSIZE; + else + { + errno = ENOMEM; + return NULL; + } + } +} diff --git a/src/bin/findutils/gnulib/lib/areadlink.h b/src/bin/findutils/gnulib/lib/areadlink.h new file mode 100644 index 0000000000..8720ed9a61 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/areadlink.h @@ -0,0 +1,23 @@ +/* Read symbolic links without size limitation. + + Copyright (C) 2001, 2003, 2004, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Jim Meyering */ + +#include + +extern char *areadlink (char const *filename); +extern char *areadlink_with_size (char const *filename, size_t size_hint); diff --git a/src/bin/findutils/gnulib/lib/argmatch.c b/src/bin/findutils/gnulib/lib/argmatch.c new file mode 100644 index 0000000000..925449bfd4 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/argmatch.c @@ -0,0 +1,277 @@ +/* argmatch.c -- find a match for a string in an array + + Copyright (C) 1990, 1998, 1999, 2001, 2002, 2003, 2004, 2005, 2006, 2007 + Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by David MacKenzie + Modified by Akim Demaille */ + +#include + +/* Specification. */ +#include "argmatch.h" + +#include +#include +#include +#include + +#include "gettext.h" +#define _(msgid) gettext (msgid) + +#include "error.h" +#include "quotearg.h" +#include "quote.h" + +#if USE_UNLOCKED_IO +# include "unlocked-io.h" +#endif + +/* When reporting an invalid argument, show nonprinting characters + by using the quoting style ARGMATCH_QUOTING_STYLE. Do not use + literal_quoting_style. */ +#ifndef ARGMATCH_QUOTING_STYLE +# define ARGMATCH_QUOTING_STYLE locale_quoting_style +#endif + +/* Non failing version of argmatch call this function after failing. */ +#ifndef ARGMATCH_DIE +# include "exitfail.h" +# define ARGMATCH_DIE exit (exit_failure) +#endif + +#ifdef ARGMATCH_DIE_DECL +ARGMATCH_DIE_DECL; +#endif + +static void +__argmatch_die (void) +{ + ARGMATCH_DIE; +} + +/* Used by XARGMATCH and XARGCASEMATCH. See description in argmatch.h. + Default to __argmatch_die, but allow caller to change this at run-time. */ +argmatch_exit_fn argmatch_die = __argmatch_die; + + +/* If ARG is an unambiguous match for an element of the + NULL-terminated array ARGLIST, return the index in ARGLIST + of the matched element, else -1 if it does not match any element + or -2 if it is ambiguous (is a prefix of more than one element). + + If VALLIST is none null, use it to resolve ambiguities limited to + synonyms, i.e., for + "yes", "yop" -> 0 + "no", "nope" -> 1 + "y" is a valid argument, for `0', and "n" for `1'. */ + +ptrdiff_t +argmatch (const char *arg, const char *const *arglist, + const char *vallist, size_t valsize) +{ + size_t i; /* Temporary index in ARGLIST. */ + size_t arglen; /* Length of ARG. */ + ptrdiff_t matchind = -1; /* Index of first nonexact match. */ + bool ambiguous = false; /* If true, multiple nonexact match(es). */ + + arglen = strlen (arg); + + /* Test all elements for either exact match or abbreviated matches. */ + for (i = 0; arglist[i]; i++) + { + if (!strncmp (arglist[i], arg, arglen)) + { + if (strlen (arglist[i]) == arglen) + /* Exact match found. */ + return i; + else if (matchind == -1) + /* First nonexact match found. */ + matchind = i; + else + { + /* Second nonexact match found. */ + if (vallist == NULL + || memcmp (vallist + valsize * matchind, + vallist + valsize * i, valsize)) + { + /* There is a real ambiguity, or we could not + disambiguate. */ + ambiguous = true; + } + } + } + } + if (ambiguous) + return -2; + else + return matchind; +} + +/* Error reporting for argmatch. + CONTEXT is a description of the type of entity that was being matched. + VALUE is the invalid value that was given. + PROBLEM is the return value from argmatch. */ + +void +argmatch_invalid (const char *context, const char *value, ptrdiff_t problem) +{ + char const *format = (problem == -1 + ? _("invalid argument %s for %s") + : _("ambiguous argument %s for %s")); + + error (0, 0, format, quotearg_n_style (0, ARGMATCH_QUOTING_STYLE, value), + quote_n (1, context)); +} + +/* List the valid arguments for argmatch. + ARGLIST is the same as in argmatch. + VALLIST is a pointer to an array of values. + VALSIZE is the size of the elements of VALLIST */ +void +argmatch_valid (const char *const *arglist, + const char *vallist, size_t valsize) +{ + size_t i; + const char *last_val = NULL; + + /* We try to put synonyms on the same line. The assumption is that + synonyms follow each other */ + fprintf (stderr, _("Valid arguments are:")); + for (i = 0; arglist[i]; i++) + if ((i == 0) + || memcmp (last_val, vallist + valsize * i, valsize)) + { + fprintf (stderr, "\n - `%s'", arglist[i]); + last_val = vallist + valsize * i; + } + else + { + fprintf (stderr, ", `%s'", arglist[i]); + } + putc ('\n', stderr); +} + +/* Never failing versions of the previous functions. + + CONTEXT is the context for which argmatch is called (e.g., + "--version-control", or "$VERSION_CONTROL" etc.). Upon failure, + calls the (supposed never to return) function EXIT_FN. */ + +ptrdiff_t +__xargmatch_internal (const char *context, + const char *arg, const char *const *arglist, + const char *vallist, size_t valsize, + argmatch_exit_fn exit_fn) +{ + ptrdiff_t res = argmatch (arg, arglist, vallist, valsize); + if (res >= 0) + /* Success. */ + return res; + + /* We failed. Explain why. */ + argmatch_invalid (context, arg, res); + argmatch_valid (arglist, vallist, valsize); + (*exit_fn) (); + + return -1; /* To please the compilers. */ +} + +/* Look for VALUE in VALLIST, an array of objects of size VALSIZE and + return the first corresponding argument in ARGLIST */ +const char * +argmatch_to_argument (const char *value, + const char *const *arglist, + const char *vallist, size_t valsize) +{ + size_t i; + + for (i = 0; arglist[i]; i++) + if (!memcmp (value, vallist + valsize * i, valsize)) + return arglist[i]; + return NULL; +} + +#ifdef TEST +/* + * Based on "getversion.c" by David MacKenzie + */ +char *program_name; + +/* When to make backup files. */ +enum backup_type +{ + /* Never make backups. */ + no_backups, + + /* Make simple backups of every file. */ + simple_backups, + + /* Make numbered backups of files that already have numbered backups, + and simple backups of the others. */ + numbered_existing_backups, + + /* Make numbered backups of every file. */ + numbered_backups +}; + +/* Two tables describing arguments (keys) and their corresponding + values */ +static const char *const backup_args[] = +{ + "no", "none", "off", + "simple", "never", + "existing", "nil", + "numbered", "t", + 0 +}; + +static const enum backup_type backup_vals[] = +{ + no_backups, no_backups, no_backups, + simple_backups, simple_backups, + numbered_existing_backups, numbered_existing_backups, + numbered_backups, numbered_backups +}; + +int +main (int argc, const char *const *argv) +{ + const char *cp; + enum backup_type backup_type = no_backups; + + program_name = (char *) argv[0]; + + if (argc > 2) + { + fprintf (stderr, "Usage: %s [VERSION_CONTROL]\n", program_name); + exit (1); + } + + if ((cp = getenv ("VERSION_CONTROL"))) + backup_type = XARGMATCH ("$VERSION_CONTROL", cp, + backup_args, backup_vals); + + if (argc == 2) + backup_type = XARGMATCH (program_name, argv[1], + backup_args, backup_vals); + + printf ("The version control is `%s'\n", + ARGMATCH_TO_ARGUMENT (backup_type, backup_args, backup_vals)); + + return 0; +} +#endif diff --git a/src/bin/findutils/gnulib/lib/argmatch.h b/src/bin/findutils/gnulib/lib/argmatch.h new file mode 100644 index 0000000000..cc403145ac --- /dev/null +++ b/src/bin/findutils/gnulib/lib/argmatch.h @@ -0,0 +1,102 @@ +/* argmatch.h -- definitions and prototypes for argmatch.c + + Copyright (C) 1990, 1998, 1999, 2001, 2002, 2004, 2005 Free Software + Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by David MacKenzie + Modified by Akim Demaille */ + +#ifndef ARGMATCH_H_ +# define ARGMATCH_H_ 1 + +# include + +# include "verify.h" + +# define ARRAY_CARDINALITY(Array) (sizeof (Array) / sizeof *(Array)) + +/* Assert there are as many real arguments as there are values + (argument list ends with a NULL guard). */ + +# define ARGMATCH_VERIFY(Arglist, Vallist) \ + verify (ARRAY_CARDINALITY (Arglist) == ARRAY_CARDINALITY (Vallist) + 1) + +/* Return the index of the element of ARGLIST (NULL terminated) that + matches with ARG. If VALLIST is not NULL, then use it to resolve + false ambiguities (i.e., different matches of ARG but corresponding + to the same values in VALLIST). */ + +ptrdiff_t argmatch (char const *arg, char const *const *arglist, + char const *vallist, size_t valsize); + +# define ARGMATCH(Arg, Arglist, Vallist) \ + argmatch (Arg, Arglist, (char const *) (Vallist), sizeof *(Vallist)) + +/* xargmatch calls this function when it fails. This function should not + return. By default, this is a function that calls ARGMATCH_DIE which + in turn defaults to `exit (exit_failure)'. */ +typedef void (*argmatch_exit_fn) (void); +extern argmatch_exit_fn argmatch_die; + +/* Report on stderr why argmatch failed. Report correct values. */ + +void argmatch_invalid (char const *context, char const *value, + ptrdiff_t problem); + +/* Left for compatibility with the old name invalid_arg */ + +# define invalid_arg(Context, Value, Problem) \ + argmatch_invalid (Context, Value, Problem) + + + +/* Report on stderr the list of possible arguments. */ + +void argmatch_valid (char const *const *arglist, + char const *vallist, size_t valsize); + +# define ARGMATCH_VALID(Arglist, Vallist) \ + argmatch_valid (Arglist, (char const *) (Vallist), sizeof *(Vallist)) + + + +/* Same as argmatch, but upon failure, reports a explanation on the + failure, and exits using the function EXIT_FN. */ + +ptrdiff_t __xargmatch_internal (char const *context, + char const *arg, char const *const *arglist, + char const *vallist, size_t valsize, + argmatch_exit_fn exit_fn); + +/* Programmer friendly interface to __xargmatch_internal. */ + +# define XARGMATCH(Context, Arg, Arglist, Vallist) \ + ((Vallist) [__xargmatch_internal (Context, Arg, Arglist, \ + (char const *) (Vallist), \ + sizeof *(Vallist), \ + argmatch_die)]) + +/* Convert a value into a corresponding argument. */ + +char const *argmatch_to_argument (char const *value, + char const *const *arglist, + char const *vallist, size_t valsize); + +# define ARGMATCH_TO_ARGUMENT(Value, Arglist, Vallist) \ + argmatch_to_argument (Value, Arglist, \ + (char const *) (Vallist), sizeof *(Vallist)) + +#endif /* ARGMATCH_H_ */ diff --git a/src/bin/findutils/gnulib/lib/at-func.c b/src/bin/findutils/gnulib/lib/at-func.c new file mode 100644 index 0000000000..c7963fe3d2 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/at-func.c @@ -0,0 +1,85 @@ +/* Define an at-style functions like fstatat, unlinkat, fchownat, etc. + Copyright (C) 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#define CALL_FUNC(F) \ + (AT_FUNC_USE_F1_COND \ + ? AT_FUNC_F1 (F AT_FUNC_POST_FILE_ARGS) \ + : AT_FUNC_F2 (F AT_FUNC_POST_FILE_ARGS)) + +/* Call AT_FUNC_F1 or AT_FUNC_F2 (testing AT_FUNC_USE_F1_COND to + determine which) to operate on FILE, which is in the directory + open on descriptor FD. If possible, do it without changing the + working directory. Otherwise, resort to using save_cwd/fchdir, + then AT_FUNC_F?/restore_cwd. If either the save_cwd or the restore_cwd + fails, then give a diagnostic and exit nonzero. */ +int +AT_FUNC_NAME (int fd, char const *file AT_FUNC_POST_FILE_PARAM_DECLS) +{ + struct saved_cwd saved_cwd; + int saved_errno; + int err; + + if (fd == AT_FDCWD || IS_ABSOLUTE_FILE_NAME (file)) + return CALL_FUNC (file); + + { + char buf[OPENAT_BUFFER_SIZE]; + char *proc_file = openat_proc_name (buf, fd, file); + if (proc_file) + { + int proc_result = CALL_FUNC (proc_file); + int proc_errno = errno; + if (proc_file != buf) + free (proc_file); + /* If the syscall succeeds, or if it fails with an unexpected + errno value, then return right away. Otherwise, fall through + and resort to using save_cwd/restore_cwd. */ + if (0 <= proc_result) + return proc_result; + if (! EXPECTED_ERRNO (proc_errno)) + { + errno = proc_errno; + return proc_result; + } + } + } + + if (save_cwd (&saved_cwd) != 0) + openat_save_fail (errno); + + if (fchdir (fd) != 0) + { + saved_errno = errno; + free_cwd (&saved_cwd); + errno = saved_errno; + return -1; + } + + err = CALL_FUNC (file); + saved_errno = (err < 0 ? errno : 0); + + if (restore_cwd (&saved_cwd) != 0) + openat_restore_fail (errno); + + free_cwd (&saved_cwd); + + if (saved_errno) + errno = saved_errno; + return err; +} +#undef CALL_FUNC diff --git a/src/bin/findutils/gnulib/lib/basename.c b/src/bin/findutils/gnulib/lib/basename.c new file mode 100644 index 0000000000..426ed40f1a --- /dev/null +++ b/src/bin/findutils/gnulib/lib/basename.c @@ -0,0 +1,128 @@ +/* basename.c -- return the last element in a file name + + Copyright (C) 1990, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006 Free + Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "dirname.h" + +#include +#include "xalloc.h" +#include "xstrndup.h" + +/* Return the address of the last file name component of NAME. If + NAME has no relative file name components because it is a file + system root, return the empty string. */ + +char * +last_component (char const *name) +{ + char const *base = name + FILE_SYSTEM_PREFIX_LEN (name); + char const *p; + bool saw_slash = false; + + while (ISSLASH (*base)) + base++; + + for (p = base; *p; p++) + { + if (ISSLASH (*p)) + saw_slash = true; + else if (saw_slash) + { + base = p; + saw_slash = false; + } + } + + return (char *) base; +} + + +/* In general, we can't use the builtin `basename' function if available, + since it has different meanings in different environments. + In some environments the builtin `basename' modifies its argument. + + Return the last file name component of NAME, allocated with + xmalloc. On systems with drive letters, a leading "./" + distinguishes relative names that would otherwise look like a drive + letter. Unlike POSIX basename(), NAME cannot be NULL, + base_name("") returns "", and the first trailing slash is not + stripped. + + If lstat (NAME) would succeed, then { chdir (dir_name (NAME)); + lstat (base_name (NAME)); } will access the same file. Likewise, + if the sequence { chdir (dir_name (NAME)); + rename (base_name (NAME), "foo"); } succeeds, you have renamed NAME + to "foo" in the same directory NAME was in. */ + +char * +base_name (char const *name) +{ + char const *base = last_component (name); + size_t length; + + /* If there is no last component, then name is a file system root or the + empty string. */ + if (! *base) + return xstrndup (name, base_len (name)); + + /* Collapse a sequence of trailing slashes into one. */ + length = base_len (base); + if (ISSLASH (base[length])) + length++; + + /* On systems with drive letters, `a/b:c' must return `./b:c' rather + than `b:c' to avoid confusion with a drive letter. On systems + with pure POSIX semantics, this is not an issue. */ + if (FILE_SYSTEM_PREFIX_LEN (base)) + { + char *p = xmalloc (length + 3); + p[0] = '.'; + p[1] = '/'; + memcpy (p + 2, base, length); + p[length + 2] = '\0'; + return p; + } + + /* Finally, copy the basename. */ + return xstrndup (base, length); +} + +/* Return the length of the basename NAME. Typically NAME is the + value returned by base_name or last_component. Act like strlen + (NAME), except omit all trailing slashes. */ + +size_t +base_len (char const *name) +{ + size_t len; + size_t prefix_len = FILE_SYSTEM_PREFIX_LEN (name); + + for (len = strlen (name); 1 < len && ISSLASH (name[len - 1]); len--) + continue; + + if (DOUBLE_SLASH_IS_DISTINCT_ROOT && len == 1 + && ISSLASH (name[0]) && ISSLASH (name[1]) && ! name[2]) + return 2; + + if (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE && prefix_len + && len == prefix_len && ISSLASH (name[prefix_len])) + return prefix_len + 1; + + return len; +} diff --git a/src/bin/findutils/gnulib/lib/binary-io.h b/src/bin/findutils/gnulib/lib/binary-io.h new file mode 100644 index 0000000000..273d35a9a6 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/binary-io.h @@ -0,0 +1,63 @@ +/* Binary mode I/O. + Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef _BINARY_H +#define _BINARY_H + +/* For systems that distinguish between text and binary I/O. + O_BINARY is usually declared in . */ +#include + +/* The MSVC7 doesn't like to be included after '#define fileno ...', + so we include it here first. */ +#include + +#if !defined O_BINARY && defined _O_BINARY + /* For MSC-compatible compilers. */ +# define O_BINARY _O_BINARY +# define O_TEXT _O_TEXT +#endif +#ifdef __BEOS__ + /* BeOS 5 has O_BINARY and O_TEXT, but they have no effect. */ +# undef O_BINARY +# undef O_TEXT +#endif +#if O_BINARY +# if !(defined __EMX__ || defined __DJGPP__ || defined __CYGWIN__) +# define setmode _setmode +# undef fileno +# define fileno _fileno +# endif +# if defined __DJGPP__ || defined __CYGWIN__ +# include /* declares setmode() */ +# endif +# ifdef __DJGPP__ +# include /* declares isatty() */ +# /* Avoid putting stdin/stdout in binary mode if it is connected to the +# console, because that would make it impossible for the user to +# interrupt the program through Ctrl-C or Ctrl-Break. */ +# define SET_BINARY(fd) (!isatty (fd) ? (setmode (fd, O_BINARY), 0) : 0) +# else +# define SET_BINARY(fd) setmode (fd, O_BINARY) +# endif +#else + /* On reasonable systems, binary I/O is the default. */ +# undef O_BINARY +# define O_BINARY 0 +# define SET_BINARY(fd) /* nothing */ +#endif + +#endif /* _BINARY_H */ diff --git a/src/bin/findutils/gnulib/lib/canonicalize-lgpl.c b/src/bin/findutils/gnulib/lib/canonicalize-lgpl.c new file mode 100644 index 0000000000..e8d2b65ebc --- /dev/null +++ b/src/bin/findutils/gnulib/lib/canonicalize-lgpl.c @@ -0,0 +1,362 @@ +/* Return the canonical absolute name of a given file. + Copyright (C) 1996-2003, 2005-2007 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +/* Avoid a clash of our rpl_realpath() function with the prototype in + on Solaris 2.5.1. */ +#undef realpath + +#if !HAVE_CANONICALIZE_FILE_NAME || defined _LIBC + +#include + +/* Specification. */ +#include "canonicalize.h" + +#include +#include +#include + +#if HAVE_UNISTD_H || defined _LIBC +# include +#endif + +#include + +#if HAVE_SYS_PARAM_H || defined _LIBC +# include +#endif +#ifndef MAXSYMLINKS +# define MAXSYMLINKS 20 +#endif + +#include + +#include +#ifndef _LIBC +# define __set_errno(e) errno = (e) +# ifndef ENAMETOOLONG +# define ENAMETOOLONG EINVAL +# endif +#endif + +#ifdef _LIBC +# include +#else +# define SHLIB_COMPAT(lib, introduced, obsoleted) 0 +# define versioned_symbol(lib, local, symbol, version) +# define compat_symbol(lib, local, symbol, version) +# define weak_alias(local, symbol) +# define __canonicalize_file_name canonicalize_file_name +# define __realpath rpl_realpath +# include "pathmax.h" +# include "malloca.h" +# if HAVE_GETCWD +# ifdef VMS + /* We want the directory in Unix syntax, not in VMS syntax. */ +# define __getcwd(buf, max) getcwd (buf, max, 0) +# else +# define __getcwd getcwd +# endif +# else +# define __getcwd(buf, max) getwd (buf) +# endif +# define __readlink readlink + /* On systems without symbolic links, call stat() instead of lstat(). */ +# if !defined S_ISNLK && !HAVE_READLINK +# define lstat stat +# endif +#endif + +/* Return the canonical absolute name of file NAME. A canonical name + does not contain any `.', `..' components nor any repeated path + separators ('/') or symlinks. All path components must exist. If + RESOLVED is null, the result is malloc'd; otherwise, if the + canonical name is PATH_MAX chars or more, returns null with `errno' + set to ENAMETOOLONG; if the name fits in fewer than PATH_MAX chars, + returns the name in RESOLVED. If the name cannot be resolved and + RESOLVED is non-NULL, it contains the path of the first component + that cannot be resolved. If the path can be resolved, RESOLVED + holds the same value as the value returned. */ + +char * +__realpath (const char *name, char *resolved) +{ + char *rpath, *dest, *extra_buf = NULL; + const char *start, *end, *rpath_limit; + long int path_max; +#if HAVE_READLINK + int num_links = 0; +#endif + + if (name == NULL) + { + /* As per Single Unix Specification V2 we must return an error if + either parameter is a null pointer. We extend this to allow + the RESOLVED parameter to be NULL in case the we are expected to + allocate the room for the return value. */ + __set_errno (EINVAL); + return NULL; + } + + if (name[0] == '\0') + { + /* As per Single Unix Specification V2 we must return an error if + the name argument points to an empty string. */ + __set_errno (ENOENT); + return NULL; + } + +#ifdef PATH_MAX + path_max = PATH_MAX; +#else + path_max = pathconf (name, _PC_PATH_MAX); + if (path_max <= 0) + path_max = 1024; +#endif + + if (resolved == NULL) + { + rpath = malloc (path_max); + if (rpath == NULL) + { + /* It's easier to set errno to ENOMEM than to rely on the + 'malloc-posix' gnulib module. */ + errno = ENOMEM; + return NULL; + } + } + else + rpath = resolved; + rpath_limit = rpath + path_max; + + if (name[0] != '/') + { + if (!__getcwd (rpath, path_max)) + { + rpath[0] = '\0'; + goto error; + } + dest = strchr (rpath, '\0'); + } + else + { + rpath[0] = '/'; + dest = rpath + 1; + } + + for (start = end = name; *start; start = end) + { +#ifdef _LIBC + struct stat64 st; +#else + struct stat st; +#endif + + /* Skip sequence of multiple path-separators. */ + while (*start == '/') + ++start; + + /* Find end of path component. */ + for (end = start; *end && *end != '/'; ++end) + /* Nothing. */; + + if (end - start == 0) + break; + else if (end - start == 1 && start[0] == '.') + /* nothing */; + else if (end - start == 2 && start[0] == '.' && start[1] == '.') + { + /* Back up to previous component, ignore if at root already. */ + if (dest > rpath + 1) + while ((--dest)[-1] != '/'); + } + else + { + size_t new_size; + + if (dest[-1] != '/') + *dest++ = '/'; + + if (dest + (end - start) >= rpath_limit) + { + ptrdiff_t dest_offset = dest - rpath; + char *new_rpath; + + if (resolved) + { + __set_errno (ENAMETOOLONG); + if (dest > rpath + 1) + dest--; + *dest = '\0'; + goto error; + } + new_size = rpath_limit - rpath; + if (end - start + 1 > path_max) + new_size += end - start + 1; + else + new_size += path_max; + new_rpath = (char *) realloc (rpath, new_size); + if (new_rpath == NULL) + { + /* It's easier to set errno to ENOMEM than to rely on the + 'realloc-posix' gnulib module. */ + errno = ENOMEM; + goto error; + } + rpath = new_rpath; + rpath_limit = rpath + new_size; + + dest = rpath + dest_offset; + } + +#ifdef _LIBC + dest = __mempcpy (dest, start, end - start); +#else + memcpy (dest, start, end - start); + dest += end - start; +#endif + *dest = '\0'; + +#ifdef _LIBC + if (__lxstat64 (_STAT_VER, rpath, &st) < 0) +#else + if (lstat (rpath, &st) < 0) +#endif + goto error; + +#if HAVE_READLINK + if (S_ISLNK (st.st_mode)) + { + char *buf; + size_t len; + int n; + + if (++num_links > MAXSYMLINKS) + { + __set_errno (ELOOP); + goto error; + } + + buf = malloca (path_max); + if (!buf) + { + errno = ENOMEM; + goto error; + } + + n = __readlink (rpath, buf, path_max); + if (n < 0) + { + int saved_errno = errno; + freea (buf); + errno = saved_errno; + goto error; + } + buf[n] = '\0'; + + if (!extra_buf) + { + extra_buf = malloca (path_max); + if (!extra_buf) + { + freea (buf); + errno = ENOMEM; + goto error; + } + } + + len = strlen (end); + if ((long int) (n + len) >= path_max) + { + freea (buf); + __set_errno (ENAMETOOLONG); + goto error; + } + + /* Careful here, end may be a pointer into extra_buf... */ + memmove (&extra_buf[n], end, len + 1); + name = end = memcpy (extra_buf, buf, n); + + if (buf[0] == '/') + dest = rpath + 1; /* It's an absolute symlink */ + else + /* Back up to previous component, ignore if at root already: */ + if (dest > rpath + 1) + while ((--dest)[-1] != '/'); + } +#endif + } + } + if (dest > rpath + 1 && dest[-1] == '/') + --dest; + *dest = '\0'; + + if (extra_buf) + freea (extra_buf); + + return resolved ? memcpy (resolved, rpath, dest - rpath + 1) : rpath; + +error: + { + int saved_errno = errno; + if (extra_buf) + freea (extra_buf); + if (resolved) + strcpy (resolved, rpath); + else + free (rpath); + errno = saved_errno; + } + return NULL; +} +#ifdef _LIBC +versioned_symbol (libc, __realpath, realpath, GLIBC_2_3); +#endif + + +#if SHLIB_COMPAT(libc, GLIBC_2_0, GLIBC_2_3) +char * +__old_realpath (const char *name, char *resolved) +{ + if (resolved == NULL) + { + __set_errno (EINVAL); + return NULL; + } + + return __realpath (name, resolved); +} +compat_symbol (libc, __old_realpath, realpath, GLIBC_2_0); +#endif + + +char * +__canonicalize_file_name (const char *name) +{ + return __realpath (name, NULL); +} +weak_alias (__canonicalize_file_name, canonicalize_file_name) + +#else + +/* This declaration is solely to ensure that after preprocessing + this file is never empty. */ +typedef int dummy; + +#endif diff --git a/src/bin/findutils/gnulib/lib/canonicalize.c b/src/bin/findutils/gnulib/lib/canonicalize.c new file mode 100644 index 0000000000..f0a4762b78 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/canonicalize.c @@ -0,0 +1,337 @@ +/* Return the canonical absolute name of a given file. + Copyright (C) 1996-2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "canonicalize.h" + +#include +#include + +#if HAVE_SYS_PARAM_H +# include +#endif + +#include + +#include + +#include +#include + +#include "file-set.h" +#include "filenamecat.h" +#include "hash-triple.h" +#include "xalloc.h" +#include "xgetcwd.h" + +#ifndef ELOOP +# define ELOOP 0 +#endif +#ifndef __set_errno +# define __set_errno(Val) errno = (Val) +#endif + +#include "pathmax.h" +#include "areadlink.h" + +#if !HAVE_CANONICALIZE_FILE_NAME +/* Return the canonical absolute name of file NAME. A canonical name + does not contain any `.', `..' components nor any repeated file name + separators ('/') or symlinks. All components must exist. + The result is malloc'd. */ + +char * +canonicalize_file_name (const char *name) +{ +# if HAVE_RESOLVEPATH + + char *resolved, *extra_buf = NULL; + size_t resolved_size; + ssize_t resolved_len; + + if (name == NULL) + { + __set_errno (EINVAL); + return NULL; + } + + if (name[0] == '\0') + { + __set_errno (ENOENT); + return NULL; + } + + /* All known hosts with resolvepath (e.g. Solaris 7) don't turn + relative names into absolute ones, so prepend the working + directory if the file name is not absolute. */ + if (name[0] != '/') + { + char *wd; + + if (!(wd = xgetcwd ())) + return NULL; + + extra_buf = file_name_concat (wd, name, NULL); + name = extra_buf; + free (wd); + } + + resolved_size = strlen (name); + while (1) + { + resolved_size = 2 * resolved_size + 1; + resolved = xmalloc (resolved_size); + resolved_len = resolvepath (name, resolved, resolved_size); + if (resolved_len < 0) + { + free (resolved); + free (extra_buf); + return NULL; + } + if (resolved_len < resolved_size) + break; + free (resolved); + } + + free (extra_buf); + + /* NUL-terminate the resulting name. */ + resolved[resolved_len] = '\0'; + + return resolved; + +# else + + return canonicalize_filename_mode (name, CAN_EXISTING); + +# endif /* !HAVE_RESOLVEPATH */ +} +#endif /* !HAVE_CANONICALIZE_FILE_NAME */ + +/* Return true if we've already seen the triple, . + If *HT is not initialized, initialize it. */ +static bool +seen_triple (Hash_table **ht, char const *filename, struct stat const *st) +{ + if (*ht == NULL) + { + size_t initial_capacity = 7; + *ht = hash_initialize (initial_capacity, + NULL, + triple_hash, + triple_compare_ino_str, + triple_free); + if (*ht == NULL) + xalloc_die (); + } + + if (seen_file (*ht, filename, st)) + return true; + + record_file (*ht, filename, st); + return false; +} + +/* Return the canonical absolute name of file NAME. A canonical name + does not contain any `.', `..' components nor any repeated file name + separators ('/') or symlinks. Whether components must exist + or not depends on canonicalize mode. The result is malloc'd. */ + +char * +canonicalize_filename_mode (const char *name, canonicalize_mode_t can_mode) +{ + char *rname, *dest, *extra_buf = NULL; + char const *start; + char const *end; + char const *rname_limit; + size_t extra_len = 0; + Hash_table *ht = NULL; + + if (name == NULL) + { + __set_errno (EINVAL); + return NULL; + } + + if (name[0] == '\0') + { + __set_errno (ENOENT); + return NULL; + } + + if (name[0] != '/') + { + rname = xgetcwd (); + if (!rname) + return NULL; + dest = strchr (rname, '\0'); + if (dest - rname < PATH_MAX) + { + char *p = xrealloc (rname, PATH_MAX); + dest = p + (dest - rname); + rname = p; + rname_limit = rname + PATH_MAX; + } + else + { + rname_limit = dest; + } + } + else + { + rname = xmalloc (PATH_MAX); + rname_limit = rname + PATH_MAX; + rname[0] = '/'; + dest = rname + 1; + } + + for (start = end = name; *start; start = end) + { + /* Skip sequence of multiple file name separators. */ + while (*start == '/') + ++start; + + /* Find end of component. */ + for (end = start; *end && *end != '/'; ++end) + /* Nothing. */; + + if (end - start == 0) + break; + else if (end - start == 1 && start[0] == '.') + /* nothing */; + else if (end - start == 2 && start[0] == '.' && start[1] == '.') + { + /* Back up to previous component, ignore if at root already. */ + if (dest > rname + 1) + while ((--dest)[-1] != '/'); + } + else + { + struct stat st; + + if (dest[-1] != '/') + *dest++ = '/'; + + if (dest + (end - start) >= rname_limit) + { + ptrdiff_t dest_offset = dest - rname; + size_t new_size = rname_limit - rname; + + if (end - start + 1 > PATH_MAX) + new_size += end - start + 1; + else + new_size += PATH_MAX; + rname = xrealloc (rname, new_size); + rname_limit = rname + new_size; + + dest = rname + dest_offset; + } + + dest = memcpy (dest, start, end - start); + dest += end - start; + *dest = '\0'; + + if (lstat (rname, &st) != 0) + { + if (can_mode == CAN_EXISTING) + goto error; + if (can_mode == CAN_ALL_BUT_LAST && *end) + goto error; + st.st_mode = 0; + } + + if (S_ISLNK (st.st_mode)) + { + char *buf; + size_t n, len; + + /* Detect loops. We cannot use the cycle-check module here, + since it's actually possible to encounter the same symlink + more than once in a given traversal. However, encountering + the same symlink,NAME pair twice does indicate a loop. */ + if (seen_triple (&ht, name, &st)) + { + __set_errno (ELOOP); + if (can_mode == CAN_MISSING) + continue; + else + goto error; + } + + buf = areadlink_with_size (rname, st.st_size); + if (!buf) + { + if (can_mode == CAN_MISSING && errno != ENOMEM) + continue; + else + goto error; + } + + n = strlen (buf); + len = strlen (end); + + if (!extra_len) + { + extra_len = + ((n + len + 1) > PATH_MAX) ? (n + len + 1) : PATH_MAX; + extra_buf = xmalloc (extra_len); + } + else if ((n + len + 1) > extra_len) + { + extra_len = n + len + 1; + extra_buf = xrealloc (extra_buf, extra_len); + } + + /* Careful here, end may be a pointer into extra_buf... */ + memmove (&extra_buf[n], end, len + 1); + name = end = memcpy (extra_buf, buf, n); + + if (buf[0] == '/') + dest = rname + 1; /* It's an absolute symlink */ + else + /* Back up to previous component, ignore if at root already: */ + if (dest > rname + 1) + while ((--dest)[-1] != '/'); + + free (buf); + } + else + { + if (!S_ISDIR (st.st_mode) && *end && (can_mode != CAN_MISSING)) + { + errno = ENOTDIR; + goto error; + } + } + } + } + if (dest > rname + 1 && dest[-1] == '/') + --dest; + *dest = '\0'; + + free (extra_buf); + if (ht) + hash_free (ht); + return rname; + +error: + free (extra_buf); + free (rname); + if (ht) + hash_free (ht); + return NULL; +} diff --git a/src/bin/findutils/gnulib/lib/canonicalize.h b/src/bin/findutils/gnulib/lib/canonicalize.h new file mode 100644 index 0000000000..8ca4fb4226 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/canonicalize.h @@ -0,0 +1,52 @@ +/* Return the canonical absolute name of a given file. + Copyright (C) 1996-2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef CANONICALIZE_H_ +# define CANONICALIZE_H_ + +# if GNULIB_CANONICALIZE +enum canonicalize_mode_t + { + /* All components must exist. */ + CAN_EXISTING = 0, + + /* All components excluding last one must exist. */ + CAN_ALL_BUT_LAST = 1, + + /* No requirements on components existence. */ + CAN_MISSING = 2 + }; +typedef enum canonicalize_mode_t canonicalize_mode_t; + +/* Return a malloc'd string containing the canonical absolute name of + the named file. This acts like canonicalize_file_name, except that + whether components must exist depends on the canonicalize_mode_t + argument. */ +char *canonicalize_filename_mode (const char *, canonicalize_mode_t); +# endif + +# if HAVE_DECL_CANONICALIZE_FILE_NAME +# include +# else +/* Return a malloc'd string containing the canonical absolute name of + the named file. If any file name component does not exist or is a + symlink to a nonexistent file, return NULL. A canonical name does + not contain any `.', `..' components nor any repeated file name + separators ('/') or symlinks. */ +char *canonicalize_file_name (const char *); +# endif + +#endif /* !CANONICALIZE_H_ */ diff --git a/src/bin/findutils/gnulib/lib/chdir-long.c b/src/bin/findutils/gnulib/lib/chdir-long.c new file mode 100644 index 0000000000..aeae25263b --- /dev/null +++ b/src/bin/findutils/gnulib/lib/chdir-long.c @@ -0,0 +1,264 @@ +/* provide a chdir function that tries not to fail due to ENAMETOOLONG + Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include + +#include "chdir-long.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "openat.h" + +#ifndef PATH_MAX +# error "compile this file only if your system defines PATH_MAX" +#endif + +struct cd_buf +{ + int fd; +}; + +static inline void +cdb_init (struct cd_buf *cdb) +{ + cdb->fd = AT_FDCWD; +} + +static inline int +cdb_fchdir (struct cd_buf const *cdb) +{ + return fchdir (cdb->fd); +} + +static inline void +cdb_free (struct cd_buf const *cdb) +{ + if (0 <= cdb->fd) + { + bool close_fail = close (cdb->fd); + assert (! close_fail); + } +} + +/* Given a file descriptor of an open directory (or AT_FDCWD), CDB->fd, + try to open the CDB->fd-relative directory, DIR. If the open succeeds, + update CDB->fd with the resulting descriptor, close the incoming file + descriptor, and return zero. Upon failure, return -1 and set errno. */ +static int +cdb_advance_fd (struct cd_buf *cdb, char const *dir) +{ + int new_fd = openat (cdb->fd, dir, + O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK); + if (new_fd < 0) + return -1; + + cdb_free (cdb); + cdb->fd = new_fd; + + return 0; +} + +/* Return a pointer to the first non-slash in S. */ +static inline char * +find_non_slash (char const *s) +{ + size_t n_slash = strspn (s, "/"); + return (char *) s + n_slash; +} + +/* This is a function much like chdir, but without the PATH_MAX limitation + on the length of the directory name. A significant difference is that + it must be able to modify (albeit only temporarily) the directory + name. It handles an arbitrarily long directory name by operating + on manageable portions of the name. On systems without the openat + syscall, this means changing the working directory to more and more + `distant' points along the long directory name and then restoring + the working directory. If any of those attempts to save or restore + the working directory fails, this function exits nonzero. + + Note that this function may still fail with errno == ENAMETOOLONG, but + only if the specified directory name contains a component that is long + enough to provoke such a failure all by itself (e.g. if the component + has length PATH_MAX or greater on systems that define PATH_MAX). */ + +int +chdir_long (char *dir) +{ + int e = chdir (dir); + if (e == 0 || errno != ENAMETOOLONG) + return e; + + { + size_t len = strlen (dir); + char *dir_end = dir + len; + struct cd_buf cdb; + size_t n_leading_slash; + + cdb_init (&cdb); + + /* If DIR is the empty string, then the chdir above + must have failed and set errno to ENOENT. */ + assert (0 < len); + assert (PATH_MAX <= len); + + /* Count leading slashes. */ + n_leading_slash = strspn (dir, "/"); + + /* Handle any leading slashes as well as any name that matches + the regular expression, m!^//hostname[/]*! . Handling this + prefix separately usually results in a single additional + cdb_advance_fd call, but it's worthwhile, since it makes the + code in the following loop cleaner. */ + if (n_leading_slash == 2) + { + int err; + /* Find next slash. + We already know that dir[2] is neither a slash nor '\0'. */ + char *slash = memchr (dir + 3, '/', dir_end - (dir + 3)); + if (slash == NULL) + { + errno = ENAMETOOLONG; + return -1; + } + *slash = '\0'; + err = cdb_advance_fd (&cdb, dir); + *slash = '/'; + if (err != 0) + goto Fail; + dir = find_non_slash (slash + 1); + } + else if (n_leading_slash) + { + if (cdb_advance_fd (&cdb, "/") != 0) + goto Fail; + dir += n_leading_slash; + } + + assert (*dir != '/'); + assert (dir <= dir_end); + + while (PATH_MAX <= dir_end - dir) + { + int err; + /* Find a slash that is PATH_MAX or fewer bytes away from dir. + I.e. see if there is a slash that will give us a name of + length PATH_MAX-1 or less. */ + char *slash = memrchr (dir, '/', PATH_MAX); + if (slash == NULL) + { + errno = ENAMETOOLONG; + return -1; + } + + *slash = '\0'; + assert (slash - dir < PATH_MAX); + err = cdb_advance_fd (&cdb, dir); + *slash = '/'; + if (err != 0) + goto Fail; + + dir = find_non_slash (slash + 1); + } + + if (dir < dir_end) + { + if (cdb_advance_fd (&cdb, dir) != 0) + goto Fail; + } + + if (cdb_fchdir (&cdb) != 0) + goto Fail; + + cdb_free (&cdb); + return 0; + + Fail: + { + int saved_errno = errno; + cdb_free (&cdb); + errno = saved_errno; + return -1; + } + } +} + +#if TEST_CHDIR + +# include +# include "closeout.h" +# include "error.h" + +char *program_name; + +int +main (int argc, char *argv[]) +{ + char *line = NULL; + size_t n = 0; + int len; + + program_name = argv[0]; + atexit (close_stdout); + + len = getline (&line, &n, stdin); + if (len < 0) + { + int saved_errno = errno; + if (feof (stdin)) + exit (0); + + error (EXIT_FAILURE, saved_errno, + "reading standard input"); + } + else if (len == 0) + exit (0); + + if (line[len-1] == '\n') + line[len-1] = '\0'; + + if (chdir_long (line) != 0) + error (EXIT_FAILURE, errno, + "chdir_long failed: %s", line); + + if (argc <= 1) + { + /* Using `pwd' here makes sense only if it is a robust implementation, + like the one in coreutils after the 2004-04-19 changes. */ + char const *cmd = "pwd"; + execlp (cmd, (char *) NULL); + error (EXIT_FAILURE, errno, "%s", cmd); + } + + fclose (stdin); + fclose (stderr); + + exit (EXIT_SUCCESS); +} +#endif + +/* +Local Variables: +compile-command: "gcc -DTEST_CHDIR=1 -g -O -W -Wall chdir-long.c libcoreutils.a" +End: +*/ diff --git a/src/bin/findutils/gnulib/lib/chdir-long.h b/src/bin/findutils/gnulib/lib/chdir-long.h new file mode 100644 index 0000000000..5bf0bbc25c --- /dev/null +++ b/src/bin/findutils/gnulib/lib/chdir-long.h @@ -0,0 +1,34 @@ +/* provide a chdir function that tries not to fail due to ENAMETOOLONG + Copyright (C) 2004, 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Jim Meyering. */ + +#include +#include + +#ifndef PATH_MAX +# ifdef MAXPATHLEN +# define PATH_MAX MAXPATHLEN +# endif +#endif + +/* On systems without PATH_MAX, presume that chdir accepts + arbitrarily long directory names. */ +#ifndef PATH_MAX +# define chdir_long(Dir) chdir (Dir) +#else +int chdir_long (char *dir); +#endif diff --git a/src/bin/findutils/gnulib/lib/chown.c b/src/bin/findutils/gnulib/lib/chown.c new file mode 100644 index 0000000000..3582b04d67 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/chown.c @@ -0,0 +1,103 @@ +/* provide consistent interface to chown for systems that don't interpret + an ID of -1 as meaning `don't change the corresponding ID'. + + Copyright (C) 1997, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include + +/* Specification. */ +#include + +#include +#include +#include +#include +#include + +/* Below we refer to the system's chown(). */ +#undef chown + +/* The results of open() in this file are not used with fchdir, + therefore save some unnecessary work in fchdir.c. */ +#undef open +#undef close + +/* Provide a more-closely POSIX-conforming version of chown on + systems with one or both of the following problems: + - chown doesn't treat an ID of -1 as meaning + `don't change the corresponding ID'. + - chown doesn't dereference symlinks. */ + +int +rpl_chown (const char *file, uid_t uid, gid_t gid) +{ +#if CHOWN_FAILS_TO_HONOR_ID_OF_NEGATIVE_ONE + if (gid == (gid_t) -1 || uid == (uid_t) -1) + { + struct stat file_stats; + + /* Stat file to get id(s) that should remain unchanged. */ + if (stat (file, &file_stats)) + return -1; + + if (gid == (gid_t) -1) + gid = file_stats.st_gid; + + if (uid == (uid_t) -1) + uid = file_stats.st_uid; + } +#endif + +#if CHOWN_MODIFIES_SYMLINK + { + /* Handle the case in which the system-supplied chown function + does *not* follow symlinks. Instead, it changes permissions + on the symlink itself. To work around that, we open the + file (but this can fail due to lack of read or write permission) and + use fchown on the resulting descriptor. */ + int open_flags = O_NONBLOCK | O_NOCTTY; + int fd = open (file, O_RDONLY | open_flags); + if (0 <= fd + || (errno == EACCES + && 0 <= (fd = open (file, O_WRONLY | open_flags)))) + { + int result = fchown (fd, uid, gid); + int saved_errno = errno; + + /* POSIX says fchown can fail with errno == EINVAL on sockets, + so fall back on chown in that case. */ + struct stat sb; + bool fchown_socket_failure = + (result != 0 && saved_errno == EINVAL + && fstat (fd, &sb) == 0 && S_ISFIFO (sb.st_mode)); + + close (fd); + + if (! fchown_socket_failure) + { + errno = saved_errno; + return result; + } + } + else if (errno != EACCES) + return -1; + } +#endif + + return chown (file, uid, gid); +} diff --git a/src/bin/findutils/gnulib/lib/close-stream.c b/src/bin/findutils/gnulib/lib/close-stream.c new file mode 100644 index 0000000000..e2c3ac0cc4 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/close-stream.c @@ -0,0 +1,75 @@ +/* Close a stream, with nicer error checking than fclose's. + + Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2006, 2007 Free + Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "close-stream.h" + +#include +#include + +#include "fpending.h" + +#if USE_UNLOCKED_IO +# include "unlocked-io.h" +#endif + +/* Close STREAM. Return 0 if successful, EOF (setting errno) + otherwise. A failure might set errno to 0 if the error number + cannot be determined. + + If a program writes *anything* to STREAM, that program should close + STREAM and make sure that it succeeds before exiting. Otherwise, + suppose that you go to the extreme of checking the return status + of every function that does an explicit write to STREAM. The last + printf can succeed in writing to the internal stream buffer, and yet + the fclose(STREAM) could still fail (due e.g., to a disk full error) + when it tries to write out that buffered data. Thus, you would be + left with an incomplete output file and the offending program would + exit successfully. Even calling fflush is not always sufficient, + since some file systems (NFS and CODA) buffer written/flushed data + until an actual close call. + + Besides, it's wasteful to check the return value from every call + that writes to STREAM -- just let the internal stream state record + the failure. That's what the ferror test is checking below. */ + +int +close_stream (FILE *stream) +{ + bool some_pending = (__fpending (stream) != 0); + bool prev_fail = (ferror (stream) != 0); + bool fclose_fail = (fclose (stream) != 0); + + /* Return an error indication if there was a previous failure or if + fclose failed, with one exception: ignore an fclose failure if + there was no previous error, no data remains to be flushed, and + fclose failed with EBADF. That can happen when a program like cp + is invoked like this `cp a b >&-' (i.e., with standard output + closed) and doesn't generate any output (hence no previous error + and nothing to be flushed). */ + + if (prev_fail || (fclose_fail && (some_pending || errno != EBADF))) + { + if (! fclose_fail) + errno = 0; + return EOF; + } + + return 0; +} diff --git a/src/bin/findutils/gnulib/lib/close-stream.h b/src/bin/findutils/gnulib/lib/close-stream.h new file mode 100644 index 0000000000..be3d4196b0 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/close-stream.h @@ -0,0 +1,2 @@ +#include +int close_stream (FILE *stream); diff --git a/src/bin/findutils/gnulib/lib/closein.c b/src/bin/findutils/gnulib/lib/closein.c new file mode 100644 index 0000000000..c7fb581eaa --- /dev/null +++ b/src/bin/findutils/gnulib/lib/closein.c @@ -0,0 +1,111 @@ +/* Close standard input, rewinding seekable stdin if necessary. + + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "closein.h" + +#include +#include +#include +#include + +#include "gettext.h" +#define _(msgid) gettext (msgid) + +#include "close-stream.h" +#include "closeout.h" +#include "error.h" +#include "exitfail.h" +#include "freadahead.h" +#include "quotearg.h" + +static const char *file_name; + +/* Set the file name to be reported in the event an error is detected + on stdin by close_stdin. See also close_stdout_set_file_name, if + an error is detected when closing stdout. */ +void +close_stdin_set_file_name (const char *file) +{ + file_name = file; +} + +/* Close standard input, rewinding any unused input if stdin is + seekable. On error, issue a diagnostic and _exit with status + 'exit_failure'. Then call close_stdout. + + Most programs can get by with close_stdout. close_stdin is only + needed when a program wants to guarantee that partially read input + from seekable stdin is not consumed, for any subsequent clients. + For example, POSIX requires that these two commands behave alike: + + (sed -ne 1q; cat) < file + tail -n 1 file + + Since close_stdin is commonly registered via 'atexit', POSIX + and the C standard both say that it should not call 'exit', + because the behavior is undefined if 'exit' is called more than + once. So it calls '_exit' instead of 'exit'. If close_stdin + is registered via atexit before other functions are registered, + the other functions can act before this _exit is invoked. + + Applications that use close_stdout should flush any streams other + than stdin, stdout, and stderr before exiting, since the call to + _exit will bypass other buffer flushing. Applications should be + flushing and closing other streams anyway, to check for I/O errors. + Also, applications should not use tmpfile, since _exit can bypass + the removal of these files. + + It's important to detect such failures and exit nonzero because many + tools (most notably `make' and other build-management systems) depend + on being able to detect failure in other tools via their exit status. */ + +void +close_stdin (void) +{ + bool fail = false; + + /* There is no need to flush stdin if we can determine quickly that stdin's + input buffer is empty; in this case we know that if stdin is seekable, + fseeko (stdin, 0, SEEK_CUR) == lseek (0, 0, SEEK_CUR). */ + if (freadahead (stdin) > 0) + { + /* Only attempt flush if stdin is seekable, as fflush is entitled to + fail on non-seekable streams. */ + if (fseeko (stdin, 0, SEEK_CUR) == 0 && fflush (stdin) != 0) + fail = true; + } + if (close_stream (stdin) != 0) + fail = true; + if (fail) + { + /* Report failure, but defer exit until after closing stdout, + since the failure report should still be flushed. */ + char const *close_error = _("error closing file"); + if (file_name) + error (0, errno, "%s: %s", quotearg_colon (file_name), + close_error); + else + error (0, errno, "%s", close_error); + } + + close_stdout (); + + if (fail) + _exit (exit_failure); +} diff --git a/src/bin/findutils/gnulib/lib/closein.h b/src/bin/findutils/gnulib/lib/closein.h new file mode 100644 index 0000000000..837ead641d --- /dev/null +++ b/src/bin/findutils/gnulib/lib/closein.h @@ -0,0 +1,32 @@ +/* Close standard input, rewinding seekable stdin if necessary. + + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef _GL_CLOSEIN_H +# define _GL_CLOSEIN_H 1 + +# ifdef __cplusplus +extern "C" { +# endif + +void close_stdin_set_file_name (const char *file); +void close_stdin (void); + +# ifdef __cplusplus +} +# endif + +#endif diff --git a/src/bin/findutils/gnulib/lib/closeout.c b/src/bin/findutils/gnulib/lib/closeout.c new file mode 100644 index 0000000000..69ddb8b239 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/closeout.c @@ -0,0 +1,85 @@ +/* Close standard output and standard error, exiting with a diagnostic on error. + + Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2006 Free + Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "closeout.h" + +#include +#include +#include + +#include "gettext.h" +#define _(msgid) gettext (msgid) + +#include "close-stream.h" +#include "error.h" +#include "exitfail.h" +#include "quotearg.h" + +static const char *file_name; + +/* Set the file name to be reported in the event an error is detected + by close_stdout. */ +void +close_stdout_set_file_name (const char *file) +{ + file_name = file; +} + +/* Close standard output. On error, issue a diagnostic and _exit + with status 'exit_failure'. + + Also close standard error. On error, _exit with status 'exit_failure'. + + Since close_stdout is commonly registered via 'atexit', POSIX + and the C standard both say that it should not call 'exit', + because the behavior is undefined if 'exit' is called more than + once. So it calls '_exit' instead of 'exit'. If close_stdout + is registered via atexit before other functions are registered, + the other functions can act before this _exit is invoked. + + Applications that use close_stdout should flush any streams + other than stdout and stderr before exiting, since the call to + _exit will bypass other buffer flushing. Applications should + be flushing and closing other streams anyway, to check for I/O + errors. Also, applications should not use tmpfile, since _exit + can bypass the removal of these files. + + It's important to detect such failures and exit nonzero because many + tools (most notably `make' and other build-management systems) depend + on being able to detect failure in other tools via their exit status. */ + +void +close_stdout (void) +{ + if (close_stream (stdout) != 0) + { + char const *write_error = _("write error"); + if (file_name) + error (0, errno, "%s: %s", quotearg_colon (file_name), + write_error); + else + error (0, errno, "%s", write_error); + + _exit (exit_failure); + } + + if (close_stream (stderr) != 0) + _exit (exit_failure); +} diff --git a/src/bin/findutils/gnulib/lib/closeout.h b/src/bin/findutils/gnulib/lib/closeout.h new file mode 100644 index 0000000000..fa7adc3113 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/closeout.h @@ -0,0 +1,32 @@ +/* Close standard output and standard error. + + Copyright (C) 1998, 2000, 2003, 2004, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef CLOSEOUT_H +# define CLOSEOUT_H 1 + +# ifdef __cplusplus +extern "C" { +# endif + +void close_stdout_set_file_name (const char *file); +void close_stdout (void); + +# ifdef __cplusplus +} +# endif + +#endif diff --git a/src/bin/findutils/gnulib/lib/configmake.h b/src/bin/findutils/gnulib/lib/configmake.h new file mode 100644 index 0000000000..99d2914cee --- /dev/null +++ b/src/bin/findutils/gnulib/lib/configmake.h @@ -0,0 +1,25 @@ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +#define PREFIX "/usr/local" +#define EXEC_PREFIX "/usr/local" +#define BINDIR "/usr/local/bin" +#define SBINDIR "/usr/local/sbin" +#define LIBEXECDIR "/usr/local/libexec" +#define DATAROOTDIR "/usr/local/share" +#define DATADIR "/usr/local/share" +#define SYSCONFDIR "/usr/local/etc" +#define SHAREDSTATEDIR "/usr/local/com" +#define LOCALSTATEDIR "/usr/local/var" +#define INCLUDEDIR "/usr/local/include" +#define OLDINCLUDEDIR "/usr/include" +#define DOCDIR "/usr/local/share/doc/findutils" +#define INFODIR "/usr/local/share/info" +#define HTMLDIR "/usr/local/share/doc/findutils" +#define DVIDIR "/usr/local/share/doc/findutils" +#define PDFDIR "/usr/local/share/doc/findutils" +#define PSDIR "/usr/local/share/doc/findutils" +#define LIBDIR "/usr/local/lib" +#define LOCALEDIR "/usr/local/share/locale" +#define MANDIR "/usr/local/share/man" +#define PKGDATADIR "/usr/local/share/findutils" +#define PKGINCLUDEDIR "/usr/local/include/findutils" +#define PKGLIBDIR "/usr/local/lib/findutils" diff --git a/src/bin/findutils/gnulib/lib/creat-safer.c b/src/bin/findutils/gnulib/lib/creat-safer.c new file mode 100644 index 0000000000..fc314ba432 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/creat-safer.c @@ -0,0 +1,31 @@ +/* Invoke creat, but avoid some glitches. + + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Jim Meyering. */ + +#include + +#include "fcntl-safer.h" + +#include +#include "unistd-safer.h" + +int +creat_safer (char const *file, mode_t mode) +{ + return fd_safer (creat (file, mode)); +} diff --git a/src/bin/findutils/gnulib/lib/dirent.in.h b/src/bin/findutils/gnulib/lib/dirent.in.h new file mode 100644 index 0000000000..db3de95113 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/dirent.in.h @@ -0,0 +1,45 @@ +/* Wrapper around . + Copyright (C) 2006-2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef _GL_DIRENT_H + +/* The include_next requires a split double-inclusion guard. */ +#@INCLUDE_NEXT@ @NEXT_DIRENT_H@ + +#ifndef _GL_DIRENT_H +#define _GL_DIRENT_H + + +/* Declare overridden functions. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if @REPLACE_FCHDIR@ +# define opendir rpl_opendir +extern DIR * opendir (const char *); +# define closedir rpl_closedir +extern int closedir (DIR *); +#endif + +#ifdef __cplusplus +} +#endif + + +#endif /* _GL_DIRENT_H */ +#endif /* _GL_DIRENT_H */ diff --git a/src/bin/findutils/gnulib/lib/dirfd.c b/src/bin/findutils/gnulib/lib/dirfd.c new file mode 100644 index 0000000000..18f5154a06 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/dirfd.c @@ -0,0 +1,28 @@ +/* dirfd.c -- return the file descriptor associated with an open DIR* + + Copyright (C) 2001, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Jim Meyering. */ + +#include + +#include "dirfd.h" + +int +dirfd (DIR const *dir_p) +{ + return DIR_TO_FD (dir_p); +} diff --git a/src/bin/findutils/gnulib/lib/dirfd.h b/src/bin/findutils/gnulib/lib/dirfd.h new file mode 100644 index 0000000000..2c2b21d235 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/dirfd.h @@ -0,0 +1,28 @@ +/* Declare dirfd, if necessary. + Copyright (C) 2001, 2002, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + Written by Jim Meyering. */ + +#include + +#include + +#ifndef HAVE_DECL_DIRFD +"this configure-time declaration test was not run" +#endif +#if !HAVE_DECL_DIRFD && !defined dirfd +int dirfd (DIR const *); +#endif diff --git a/src/bin/findutils/gnulib/lib/dirname.c b/src/bin/findutils/gnulib/lib/dirname.c new file mode 100644 index 0000000000..c27e5b5d8b --- /dev/null +++ b/src/bin/findutils/gnulib/lib/dirname.c @@ -0,0 +1,84 @@ +/* dirname.c -- return all but the last element in a file name + + Copyright (C) 1990, 1998, 2000, 2001, 2003, 2004, 2005, 2006 Free Software + Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "dirname.h" + +#include +#include "xalloc.h" + +/* Return the length of the prefix of FILE that will be used by + dir_name. If FILE is in the working directory, this returns zero + even though `dir_name (FILE)' will return ".". Works properly even + if there are trailing slashes (by effectively ignoring them). */ + +size_t +dir_len (char const *file) +{ + size_t prefix_length = FILE_SYSTEM_PREFIX_LEN (file); + size_t length; + + /* Advance prefix_length beyond important leading slashes. */ + prefix_length += (prefix_length != 0 + ? (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE + && ISSLASH (file[prefix_length])) + : (ISSLASH (file[0]) + ? ((DOUBLE_SLASH_IS_DISTINCT_ROOT + && ISSLASH (file[1]) && ! ISSLASH (file[2]) + ? 2 : 1)) + : 0)); + + /* Strip the basename and any redundant slashes before it. */ + for (length = last_component (file) - file; + prefix_length < length; length--) + if (! ISSLASH (file[length - 1])) + break; + return length; +} + + +/* In general, we can't use the builtin `dirname' function if available, + since it has different meanings in different environments. + In some environments the builtin `dirname' modifies its argument. + + Return the leading directories part of FILE, allocated with xmalloc. + Works properly even if there are trailing slashes (by effectively + ignoring them). Unlike POSIX dirname(), FILE cannot be NULL. + + If lstat (FILE) would succeed, then { chdir (dir_name (FILE)); + lstat (base_name (FILE)); } will access the same file. Likewise, + if the sequence { chdir (dir_name (FILE)); + rename (base_name (FILE), "foo"); } succeeds, you have renamed FILE + to "foo" in the same directory FILE was in. */ + +char * +dir_name (char const *file) +{ + size_t length = dir_len (file); + bool append_dot = (length == 0 + || (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE + && length == FILE_SYSTEM_PREFIX_LEN (file) + && file[2] != '\0' && ! ISSLASH (file[2]))); + char *dir = xmalloc (length + append_dot + 1); + memcpy (dir, file, length); + if (append_dot) + dir[length++] = '.'; + dir[length] = '\0'; + return dir; +} diff --git a/src/bin/findutils/gnulib/lib/dirname.h b/src/bin/findutils/gnulib/lib/dirname.h new file mode 100644 index 0000000000..f592350b81 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/dirname.h @@ -0,0 +1,69 @@ +/* Take file names apart into directory and base names. + + Copyright (C) 1998, 2001, 2003-2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef DIRNAME_H_ +# define DIRNAME_H_ 1 + +# include +# include + +# ifndef DIRECTORY_SEPARATOR +# define DIRECTORY_SEPARATOR '/' +# endif + +# ifndef ISSLASH +# define ISSLASH(C) ((C) == DIRECTORY_SEPARATOR) +# endif + +# ifndef FILE_SYSTEM_PREFIX_LEN +# if FILE_SYSTEM_ACCEPTS_DRIVE_LETTER_PREFIX + /* This internal macro assumes ASCII, but all hosts that support drive + letters use ASCII. */ +# define _IS_DRIVE_LETTER(c) (((unsigned int) (c) | ('a' - 'A')) - 'a' \ + <= 'z' - 'a') +# define FILE_SYSTEM_PREFIX_LEN(Filename) \ + (_IS_DRIVE_LETTER ((Filename)[0]) && (Filename)[1] == ':' ? 2 : 0) +# else +# define FILE_SYSTEM_PREFIX_LEN(Filename) 0 +# endif +# endif + +# ifndef FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE +# define FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE 0 +# endif + +# ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT +# define DOUBLE_SLASH_IS_DISTINCT_ROOT 0 +# endif + +# if FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE +# define IS_ABSOLUTE_FILE_NAME(F) ISSLASH ((F)[FILE_SYSTEM_PREFIX_LEN (F)]) +# else +# define IS_ABSOLUTE_FILE_NAME(F) \ + (ISSLASH ((F)[0]) || 0 < FILE_SYSTEM_PREFIX_LEN (F)) +# endif +# define IS_RELATIVE_FILE_NAME(F) (! IS_ABSOLUTE_FILE_NAME (F)) + +char *base_name (char const *file); +char *dir_name (char const *file); +size_t base_len (char const *file); +size_t dir_len (char const *file); +char *last_component (char const *file); + +bool strip_trailing_slashes (char *file); + +#endif /* not DIRNAME_H_ */ diff --git a/src/bin/findutils/gnulib/lib/dup-safer.c b/src/bin/findutils/gnulib/lib/dup-safer.c new file mode 100644 index 0000000000..a6908511ac --- /dev/null +++ b/src/bin/findutils/gnulib/lib/dup-safer.c @@ -0,0 +1,44 @@ +/* Invoke dup, but avoid some glitches. + + Copyright (C) 2001, 2004, 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert. */ + +#include + +#include "unistd-safer.h" + +#include + +#include +#ifndef STDERR_FILENO +# define STDERR_FILENO 2 +#endif + +/* Like dup, but do not return STDIN_FILENO, STDOUT_FILENO, or + STDERR_FILENO. */ + +int +dup_safer (int fd) +{ +#if defined F_DUPFD && !defined FCHDIR_REPLACEMENT + return fcntl (fd, F_DUPFD, STDERR_FILENO + 1); +#else + /* fd_safer calls us back, but eventually the recursion unwinds and + does the right thing. */ + return fd_safer (dup (fd)); +#endif +} diff --git a/src/bin/findutils/gnulib/lib/dup2.c b/src/bin/findutils/gnulib/lib/dup2.c new file mode 100644 index 0000000000..09990823be --- /dev/null +++ b/src/bin/findutils/gnulib/lib/dup2.c @@ -0,0 +1,57 @@ +/* Duplicate an open file descriptor to a specified file descriptor. + + Copyright (C) 1999, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Paul Eggert */ + +#include + +/* Specification. */ +#include + +#include +#include + +#ifndef F_DUPFD +static int +dupfd (int fd, int desired_fd) +{ + int duplicated_fd = dup (fd); + if (duplicated_fd < 0 || duplicated_fd == desired_fd) + return duplicated_fd; + else + { + int r = dupfd (fd, desired_fd); + int e = errno; + close (duplicated_fd); + errno = e; + return r; + } +} +#endif + +int +dup2 (int fd, int desired_fd) +{ + if (fd == desired_fd) + return fd; + close (desired_fd); +#ifdef F_DUPFD + return fcntl (fd, F_DUPFD, desired_fd); +#else + return dupfd (fd, desired_fd); +#endif +} diff --git a/src/bin/findutils/gnulib/lib/error.c b/src/bin/findutils/gnulib/lib/error.c new file mode 100644 index 0000000000..3177bd5d2c --- /dev/null +++ b/src/bin/findutils/gnulib/lib/error.c @@ -0,0 +1,338 @@ +/* Error handler for noninteractive utilities + Copyright (C) 1990-1998, 2000-2007 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by David MacKenzie . */ + +#if !_LIBC +# include +#endif + +#include "error.h" + +#include +#include +#include +#include + +#if !_LIBC && ENABLE_NLS +# include "gettext.h" +# define _(msgid) gettext (msgid) +#endif + +#ifdef _LIBC +# include +# include +# include +# include +# define mbsrtowcs __mbsrtowcs +#endif + +#if USE_UNLOCKED_IO +# include "unlocked-io.h" +#endif + +#ifndef _ +# define _(String) String +#endif + +/* If NULL, error will flush stdout, then print on stderr the program + name, a colon and a space. Otherwise, error will call this + function without parameters instead. */ +void (*error_print_progname) (void); + +/* This variable is incremented each time `error' is called. */ +unsigned int error_message_count; + +#ifdef _LIBC +/* In the GNU C library, there is a predefined variable for this. */ + +# define program_name program_invocation_name +# include +# include +# include + +/* In GNU libc we want do not want to use the common name `error' directly. + Instead make it a weak alias. */ +extern void __error (int status, int errnum, const char *message, ...) + __attribute__ ((__format__ (__printf__, 3, 4))); +extern void __error_at_line (int status, int errnum, const char *file_name, + unsigned int line_number, const char *message, + ...) + __attribute__ ((__format__ (__printf__, 5, 6)));; +# define error __error +# define error_at_line __error_at_line + +# include +# define fflush(s) INTUSE(_IO_fflush) (s) +# undef putc +# define putc(c, fp) INTUSE(_IO_putc) (c, fp) + +# include + +#else /* not _LIBC */ + +# if !HAVE_DECL_STRERROR_R && STRERROR_R_CHAR_P +# ifndef HAVE_DECL_STRERROR_R +"this configure-time declaration test was not run" +# endif +char *strerror_r (); +# endif + +/* The calling program should define program_name and set it to the + name of the executing program. */ +extern char *program_name; + +# if HAVE_STRERROR_R || defined strerror_r +# define __strerror_r strerror_r +# endif /* HAVE_STRERROR_R || defined strerror_r */ +#endif /* not _LIBC */ + +static void +print_errno_message (int errnum) +{ + char const *s; + +#if defined HAVE_STRERROR_R || _LIBC + char errbuf[1024]; +# if STRERROR_R_CHAR_P || _LIBC + s = __strerror_r (errnum, errbuf, sizeof errbuf); +# else + if (__strerror_r (errnum, errbuf, sizeof errbuf) == 0) + s = errbuf; + else + s = 0; +# endif +#else + s = strerror (errnum); +#endif + +#if !_LIBC + if (! s) + s = _("Unknown system error"); +#endif + +#if _LIBC + __fxprintf (NULL, ": %s", s); +#else + fprintf (stderr, ": %s", s); +#endif +} + +static void +error_tail (int status, int errnum, const char *message, va_list args) +{ +#if _LIBC + if (_IO_fwide (stderr, 0) > 0) + { +# define ALLOCA_LIMIT 2000 + size_t len = strlen (message) + 1; + wchar_t *wmessage = NULL; + mbstate_t st; + size_t res; + const char *tmp; + bool use_malloc = false; + + while (1) + { + if (__libc_use_alloca (len * sizeof (wchar_t))) + wmessage = (wchar_t *) alloca (len * sizeof (wchar_t)); + else + { + if (!use_malloc) + wmessage = NULL; + + wchar_t *p = (wchar_t *) realloc (wmessage, + len * sizeof (wchar_t)); + if (p == NULL) + { + free (wmessage); + fputws_unlocked (L"out of memory\n", stderr); + return; + } + wmessage = p; + use_malloc = true; + } + + memset (&st, '\0', sizeof (st)); + tmp = message; + + res = mbsrtowcs (wmessage, &tmp, len, &st); + if (res != len) + break; + + if (__builtin_expect (len >= SIZE_MAX / 2, 0)) + { + /* This really should not happen if everything is fine. */ + res = (size_t) -1; + break; + } + + len *= 2; + } + + if (res == (size_t) -1) + { + /* The string cannot be converted. */ + if (use_malloc) + { + free (wmessage); + use_malloc = false; + } + wmessage = (wchar_t *) L"???"; + } + + __vfwprintf (stderr, wmessage, args); + + if (use_malloc) + free (wmessage); + } + else +#endif + vfprintf (stderr, message, args); + va_end (args); + + ++error_message_count; + if (errnum) + print_errno_message (errnum); +#if _LIBC + __fxprintf (NULL, "\n"); +#else + putc ('\n', stderr); +#endif + fflush (stderr); + if (status) + exit (status); +} + + +/* Print the program name and error message MESSAGE, which is a printf-style + format string with optional args. + If ERRNUM is nonzero, print its corresponding system error message. + Exit with status STATUS if it is nonzero. */ +void +error (int status, int errnum, const char *message, ...) +{ + va_list args; + +#if defined _LIBC && defined __libc_ptf_call + /* We do not want this call to be cut short by a thread + cancellation. Therefore disable cancellation for now. */ + int state = PTHREAD_CANCEL_ENABLE; + __libc_ptf_call (pthread_setcancelstate, (PTHREAD_CANCEL_DISABLE, &state), + 0); +#endif + + fflush (stdout); +#ifdef _LIBC + _IO_flockfile (stderr); +#endif + if (error_print_progname) + (*error_print_progname) (); + else + { +#if _LIBC + __fxprintf (NULL, "%s: ", program_name); +#else + fprintf (stderr, "%s: ", program_name); +#endif + } + + va_start (args, message); + error_tail (status, errnum, message, args); + +#ifdef _LIBC + _IO_funlockfile (stderr); +# ifdef __libc_ptf_call + __libc_ptf_call (pthread_setcancelstate, (state, NULL), 0); +# endif +#endif +} + +/* Sometimes we want to have at most one error per line. This + variable controls whether this mode is selected or not. */ +int error_one_per_line; + +void +error_at_line (int status, int errnum, const char *file_name, + unsigned int line_number, const char *message, ...) +{ + va_list args; + + if (error_one_per_line) + { + static const char *old_file_name; + static unsigned int old_line_number; + + if (old_line_number == line_number + && (file_name == old_file_name + || strcmp (old_file_name, file_name) == 0)) + /* Simply return and print nothing. */ + return; + + old_file_name = file_name; + old_line_number = line_number; + } + +#if defined _LIBC && defined __libc_ptf_call + /* We do not want this call to be cut short by a thread + cancellation. Therefore disable cancellation for now. */ + int state = PTHREAD_CANCEL_ENABLE; + __libc_ptf_call (pthread_setcancelstate, (PTHREAD_CANCEL_DISABLE, &state), + 0); +#endif + + fflush (stdout); +#ifdef _LIBC + _IO_flockfile (stderr); +#endif + if (error_print_progname) + (*error_print_progname) (); + else + { +#if _LIBC + __fxprintf (NULL, "%s:", program_name); +#else + fprintf (stderr, "%s:", program_name); +#endif + } + +#if _LIBC + __fxprintf (NULL, file_name != NULL ? "%s:%d: " : " ", + file_name, line_number); +#else + fprintf (stderr, file_name != NULL ? "%s:%d: " : " ", + file_name, line_number); +#endif + + va_start (args, message); + error_tail (status, errnum, message, args); + +#ifdef _LIBC + _IO_funlockfile (stderr); +# ifdef __libc_ptf_call + __libc_ptf_call (pthread_setcancelstate, (state, NULL), 0); +# endif +#endif +} + +#ifdef _LIBC +/* Make the weak alias. */ +# undef error +# undef error_at_line +weak_alias (__error, error) +weak_alias (__error_at_line, error_at_line) +#endif diff --git a/src/bin/findutils/gnulib/lib/error.h b/src/bin/findutils/gnulib/lib/error.h new file mode 100644 index 0000000000..8c215a7fd3 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/error.h @@ -0,0 +1,65 @@ +/* Declaration for error-reporting function + Copyright (C) 1995, 1996, 1997, 2003, 2006 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef _ERROR_H +#define _ERROR_H 1 + +#ifndef __attribute__ +/* This feature is available in gcc versions 2.5 and later. */ +# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__ +# define __attribute__(Spec) /* empty */ +# endif +/* The __-protected variants of `format' and `printf' attributes + are accepted by gcc versions 2.6.4 (effectively 2.7) and later. */ +# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7) +# define __format__ format +# define __printf__ printf +# endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* Print a message with `fprintf (stderr, FORMAT, ...)'; + if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM). + If STATUS is nonzero, terminate the program with `exit (STATUS)'. */ + +extern void error (int __status, int __errnum, const char *__format, ...) + __attribute__ ((__format__ (__printf__, 3, 4))); + +extern void error_at_line (int __status, int __errnum, const char *__fname, + unsigned int __lineno, const char *__format, ...) + __attribute__ ((__format__ (__printf__, 5, 6))); + +/* If NULL, error will flush stdout, then print on stderr the program + name, a colon and a space. Otherwise, error will call this + function without parameters instead. */ +extern void (*error_print_progname) (void); + +/* This variable is incremented each time `error' is called. */ +extern unsigned int error_message_count; + +/* Sometimes we want to have at most one error per line. This + variable controls whether this mode is selected or not. */ +extern int error_one_per_line; + +#ifdef __cplusplus +} +#endif + +#endif /* error.h */ diff --git a/src/bin/findutils/gnulib/lib/exitfail.c b/src/bin/findutils/gnulib/lib/exitfail.c new file mode 100644 index 0000000000..6d1fe4aea0 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/exitfail.c @@ -0,0 +1,24 @@ +/* Failure exit status + + Copyright (C) 2002, 2003, 2005, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "exitfail.h" + +#include + +int volatile exit_failure = EXIT_FAILURE; diff --git a/src/bin/findutils/gnulib/lib/exitfail.h b/src/bin/findutils/gnulib/lib/exitfail.h new file mode 100644 index 0000000000..713f2591a7 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/exitfail.h @@ -0,0 +1,18 @@ +/* Failure exit status + + Copyright (C) 2002 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +extern int volatile exit_failure; diff --git a/src/bin/findutils/gnulib/lib/fchdir.c b/src/bin/findutils/gnulib/lib/fchdir.c new file mode 100644 index 0000000000..246987c886 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fchdir.c @@ -0,0 +1,282 @@ +/* fchdir replacement. + Copyright (C) 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +/* Specification. */ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "canonicalize.h" +#include "dirfd.h" + +/* This replacement assumes that a directory is not renamed while opened + through a file descriptor. */ + +/* Array of file descriptors opened. If it points to a directory, it stores + info about this directory; otherwise it stores an errno value of ENOTDIR. */ +typedef struct +{ + char *name; /* Absolute name of the directory, or NULL. */ + int saved_errno; /* If name == NULL: The error code describing the failure + reason. */ +} dir_info_t; +static dir_info_t *dirs; +static size_t dirs_allocated; + +/* Try to ensure dirs has enough room for a slot at index fd. */ +static void +ensure_dirs_slot (size_t fd) +{ + if (fd >= dirs_allocated) + { + size_t new_allocated; + dir_info_t *new_dirs; + size_t i; + + new_allocated = 2 * dirs_allocated + 1; + if (new_allocated <= fd) + new_allocated = fd + 1; + new_dirs = + (dirs != NULL + ? (dir_info_t *) realloc (dirs, new_allocated * sizeof (dir_info_t)) + : (dir_info_t *) malloc (new_allocated * sizeof (dir_info_t))); + if (new_dirs != NULL) + { + for (i = dirs_allocated; i < new_allocated; i++) + { + new_dirs[i].name = NULL; + new_dirs[i].saved_errno = ENOTDIR; + } + dirs = new_dirs; + dirs_allocated = new_allocated; + } + } +} + +/* Override open() and close(), to keep track of the open file descriptors. */ + +int +rpl_close (int fd) +#undef close +{ + int retval = close (fd); + + if (retval >= 0 && fd >= 0 && fd < dirs_allocated) + { + if (dirs[fd].name != NULL) + free (dirs[fd].name); + dirs[fd].name = NULL; + dirs[fd].saved_errno = ENOTDIR; + } + return retval; +} + +int +rpl_open (const char *filename, int flags, ...) +#undef open +{ + mode_t mode; + int fd; + struct stat statbuf; + + mode = 0; + if (flags & O_CREAT) + { + va_list arg; + va_start (arg, flags); + + /* If mode_t is narrower than int, use the promoted type (int), + not mode_t. Use sizeof to guess whether mode_t is narrower; + we don't know of any practical counterexamples. */ + mode = (sizeof (mode_t) < sizeof (int) + ? va_arg (arg, int) + : va_arg (arg, mode_t)); + + va_end (arg); + } +#if defined GNULIB_OPEN && ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__) + if (strcmp (filename, "/dev/null") == 0) + filename = "NUL"; +#endif + fd = open (filename, flags, mode); + if (fd >= 0) + { + ensure_dirs_slot (fd); + if (fd < dirs_allocated + && fstat (fd, &statbuf) >= 0 && S_ISDIR (statbuf.st_mode)) + { + dirs[fd].name = canonicalize_file_name (filename); + if (dirs[fd].name == NULL) + dirs[fd].saved_errno = errno; + } + } + return fd; +} + +/* Override opendir() and closedir(), to keep track of the open file + descriptors. Needed because there is a function dirfd(). */ + +int +rpl_closedir (DIR *dp) +#undef closedir +{ + int fd = dirfd (dp); + int retval = closedir (dp); + + if (retval >= 0 && fd >= 0 && fd < dirs_allocated) + { + if (dirs[fd].name != NULL) + free (dirs[fd].name); + dirs[fd].name = NULL; + dirs[fd].saved_errno = ENOTDIR; + } + return retval; +} + +DIR * +rpl_opendir (const char *filename) +#undef opendir +{ + DIR *dp; + + dp = opendir (filename); + if (dp != NULL) + { + int fd = dirfd (dp); + if (fd >= 0) + { + ensure_dirs_slot (fd); + if (fd < dirs_allocated) + { + dirs[fd].name = canonicalize_file_name (filename); + if (dirs[fd].name == NULL) + dirs[fd].saved_errno = errno; + } + } + } + return dp; +} + +/* Override dup() and dup2(), to keep track of open file descriptors. */ + +int +rpl_dup (int oldfd) +#undef dup +{ + int newfd = dup (oldfd); + + if (oldfd >= 0 && newfd >= 0) + { + ensure_dirs_slot (newfd); + if (newfd < dirs_allocated) + { + if (oldfd < dirs_allocated) + { + if (dirs[oldfd].name != NULL) + { + dirs[newfd].name = strdup (dirs[oldfd].name); + if (dirs[newfd].name == NULL) + dirs[newfd].saved_errno = ENOMEM; + } + else + { + dirs[newfd].name = NULL; + dirs[newfd].saved_errno = dirs[oldfd].saved_errno; + } + } + else + { + dirs[newfd].name = NULL; + dirs[newfd].saved_errno = ENOMEM; + } + } + } + return newfd; +} + +int +rpl_dup2 (int oldfd, int newfd) +#undef dup2 +{ + int retval = dup2 (oldfd, newfd); + + if (retval >= 0 && oldfd >= 0 && newfd >= 0 && newfd != oldfd) + { + ensure_dirs_slot (newfd); + if (newfd < dirs_allocated) + { + if (oldfd < dirs_allocated) + { + if (dirs[oldfd].name != NULL) + { + dirs[newfd].name = strdup (dirs[oldfd].name); + if (dirs[newfd].name == NULL) + dirs[newfd].saved_errno = ENOMEM; + } + else + { + dirs[newfd].name = NULL; + dirs[newfd].saved_errno = dirs[oldfd].saved_errno; + } + } + else + { + dirs[newfd].name = NULL; + dirs[newfd].saved_errno = ENOMEM; + } + } + } + return retval; +} + +/* Implement fchdir() in terms of chdir(). */ + +int +fchdir (int fd) +{ + if (fd >= 0) + { + if (fd < dirs_allocated) + { + if (dirs[fd].name != NULL) + return chdir (dirs[fd].name); + else + { + errno = dirs[fd].saved_errno; + return -1; + } + } + else + { + errno = ENOMEM; + return -1; + } + } + else + { + errno = EBADF; + return -1; + } +} diff --git a/src/bin/findutils/gnulib/lib/fchmodat.c b/src/bin/findutils/gnulib/lib/fchmodat.c new file mode 100644 index 0000000000..935bdcbca1 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fchmodat.c @@ -0,0 +1,49 @@ +/* Change the protections of file relative to an open directory. + Copyright (C) 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include + +#include "openat.h" +#include "dirname.h" /* solely for definition of IS_ABSOLUTE_FILE_NAME */ +#include "save-cwd.h" +#include "openat-priv.h" + +#ifndef HAVE_LCHMOD +/* Use a different name, to avoid conflicting with any + system-supplied declaration. */ +# undef lchmod +# define lchmod lchmod_rpl +static int lchmod (char const *f, mode_t m) { errno = ENOSYS; return -1; } +#endif + +/* Solaris 10 has no function like this. + Invoke chmod or lchmod on file, FILE, using mode MODE, in the directory + open on descriptor FD. If possible, do it without changing the + working directory. Otherwise, resort to using save_cwd/fchdir, + then mkdir/restore_cwd. If either the save_cwd or the restore_cwd + fails, then give a diagnostic and exit nonzero. + Note that an attempt to use a FLAG value of AT_SYMLINK_NOFOLLOW + on a system without lchmod support causes this function to fail. */ + +#define AT_FUNC_NAME fchmodat +#define AT_FUNC_F1 lchmod +#define AT_FUNC_F2 chmod +#define AT_FUNC_USE_F1_COND flag == AT_SYMLINK_NOFOLLOW +#define AT_FUNC_POST_FILE_PARAM_DECLS , mode_t mode, int flag +#define AT_FUNC_POST_FILE_ARGS , mode +#include "at-func.c" diff --git a/src/bin/findutils/gnulib/lib/fchown-stub.c b/src/bin/findutils/gnulib/lib/fchown-stub.c new file mode 100644 index 0000000000..6be750b829 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fchown-stub.c @@ -0,0 +1,16 @@ +#include + +#include +#include + +/* A trivial substitute for `fchown'. + + DJGPP 2.03 and earlier (and perhaps later) don't have `fchown', + so we pretend no-one has permission for this operation. */ + +int +fchown (int fd, uid_t uid, gid_t gid) +{ + errno = EPERM; + return -1; +} diff --git a/src/bin/findutils/gnulib/lib/fchownat.c b/src/bin/findutils/gnulib/lib/fchownat.c new file mode 100644 index 0000000000..a1d5e60f21 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fchownat.c @@ -0,0 +1,48 @@ +/* This function serves as replacement for a missing fchownat function, + as well as a work around for the fchownat bug in glibc-2.4: + + when the buggy fchownat-with-AT_SYMLINK_NOFOLLOW operates on a symlink, it + mistakenly affects the symlink referent, rather than the symlink itself. + + Copyright (C) 2006-2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include + +#include "openat.h" + +#include + +#include "dirname.h" /* solely for definition of IS_ABSOLUTE_FILE_NAME */ +#include "save-cwd.h" +#include "openat-priv.h" + +/* Replacement for Solaris' function by the same name. + Invoke chown or lchown on file, FILE, using OWNER and GROUP, in the + directory open on descriptor FD. If FLAG is AT_SYMLINK_NOFOLLOW, then + use lchown, otherwise, use chown. If possible, do it without changing + the working directory. Otherwise, resort to using save_cwd/fchdir, + then mkdir/restore_cwd. If either the save_cwd or the restore_cwd + fails, then give a diagnostic and exit nonzero. */ + +#define AT_FUNC_NAME fchownat +#define AT_FUNC_F1 lchown +#define AT_FUNC_F2 chown +#define AT_FUNC_USE_F1_COND flag == AT_SYMLINK_NOFOLLOW +#define AT_FUNC_POST_FILE_PARAM_DECLS , uid_t owner, gid_t group, int flag +#define AT_FUNC_POST_FILE_ARGS , owner, group +#include "at-func.c" diff --git a/src/bin/findutils/gnulib/lib/fcntl--.h b/src/bin/findutils/gnulib/lib/fcntl--.h new file mode 100644 index 0000000000..5a6a8792d0 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fcntl--.h @@ -0,0 +1,27 @@ +/* Like fcntl.h, but redefine some names to avoid glitches. + + Copyright (C) 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert. */ + +#include +#include "fcntl-safer.h" + +#undef open +#define open open_safer + +#undef creat +#define creat creat_safer diff --git a/src/bin/findutils/gnulib/lib/fcntl-safer.h b/src/bin/findutils/gnulib/lib/fcntl-safer.h new file mode 100644 index 0000000000..99f38656d0 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fcntl-safer.h @@ -0,0 +1,23 @@ +/* Invoke fcntl-like functions, but avoid some glitches. + + Copyright (C) 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert. */ + +#include + +int open_safer (char const *, int, ...); +int creat_safer (char const *, mode_t); diff --git a/src/bin/findutils/gnulib/lib/fcntl.h b/src/bin/findutils/gnulib/lib/fcntl.h new file mode 100644 index 0000000000..67f8e77dcd --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fcntl.h @@ -0,0 +1,121 @@ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +/* Like , but with non-working flags defined to 0. + + Copyright (C) 2006-2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Paul Eggert */ + +#ifndef _GL_FCNTL_H + +#include +#include +#include +/* The include_next requires a split double-inclusion guard. */ +#include_next + +#ifndef _GL_FCNTL_H +#define _GL_FCNTL_H + + +/* Declare overridden functions. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if (0 && 0) || defined FCHDIR_REPLACEMENT +# define open rpl_open +extern int open (const char *filename, int flags, ...); +#endif + +#ifdef __cplusplus +} +#endif + + +/* Fix up the O_* macros. */ + +#if !defined O_DIRECT && defined O_DIRECTIO +/* Tru64 spells it `O_DIRECTIO'. */ +# define O_DIRECT O_DIRECTIO +#endif + +#ifndef O_DIRECT +# define O_DIRECT 0 +#endif + +#ifndef O_DIRECTORY +# define O_DIRECTORY 0 +#endif + +#ifndef O_DSYNC +# define O_DSYNC 0 +#endif + +#ifndef O_NDELAY +# define O_NDELAY 0 +#endif + +#ifndef O_NOATIME +# define O_NOATIME 0 +#endif + +#ifndef O_NONBLOCK +# define O_NONBLOCK O_NDELAY +#endif + +#ifndef O_NOCTTY +# define O_NOCTTY 0 +#endif + +#ifndef O_NOFOLLOW +# define O_NOFOLLOW 0 +#endif + +#ifndef O_NOLINKS +# define O_NOLINKS 0 +#endif + +#ifndef O_RSYNC +# define O_RSYNC 0 +#endif + +#ifndef O_SYNC +# define O_SYNC 0 +#endif + +/* For systems that distinguish between text and binary I/O. + O_BINARY is usually declared in fcntl.h */ +#if !defined O_BINARY && defined _O_BINARY + /* For MSC-compatible compilers. */ +# define O_BINARY _O_BINARY +# define O_TEXT _O_TEXT +#endif + +#ifdef __BEOS__ + /* BeOS 5 has O_BINARY and O_TEXT, but they have no effect. */ +# undef O_BINARY +# undef O_TEXT +#endif + +#ifndef O_BINARY +# define O_BINARY 0 +# define O_TEXT 0 +#endif + + +#endif /* _GL_FCNTL_H */ +#endif /* _GL_FCNTL_H */ diff --git a/src/bin/findutils/gnulib/lib/fcntl.in.h b/src/bin/findutils/gnulib/lib/fcntl.in.h new file mode 100644 index 0000000000..066a26c70e --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fcntl.in.h @@ -0,0 +1,120 @@ +/* Like , but with non-working flags defined to 0. + + Copyright (C) 2006-2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Paul Eggert */ + +#ifndef _GL_FCNTL_H + +#include +#include +#include +/* The include_next requires a split double-inclusion guard. */ +#@INCLUDE_NEXT@ @NEXT_FCNTL_H@ + +#ifndef _GL_FCNTL_H +#define _GL_FCNTL_H + + +/* Declare overridden functions. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if (@GNULIB_OPEN@ && @REPLACE_OPEN@) || defined FCHDIR_REPLACEMENT +# define open rpl_open +extern int open (const char *filename, int flags, ...); +#endif + +#ifdef __cplusplus +} +#endif + + +/* Fix up the O_* macros. */ + +#if !defined O_DIRECT && defined O_DIRECTIO +/* Tru64 spells it `O_DIRECTIO'. */ +# define O_DIRECT O_DIRECTIO +#endif + +#ifndef O_DIRECT +# define O_DIRECT 0 +#endif + +#ifndef O_DIRECTORY +# define O_DIRECTORY 0 +#endif + +#ifndef O_DSYNC +# define O_DSYNC 0 +#endif + +#ifndef O_NDELAY +# define O_NDELAY 0 +#endif + +#ifndef O_NOATIME +# define O_NOATIME 0 +#endif + +#ifndef O_NONBLOCK +# define O_NONBLOCK O_NDELAY +#endif + +#ifndef O_NOCTTY +# define O_NOCTTY 0 +#endif + +#ifndef O_NOFOLLOW +# define O_NOFOLLOW 0 +#endif + +#ifndef O_NOLINKS +# define O_NOLINKS 0 +#endif + +#ifndef O_RSYNC +# define O_RSYNC 0 +#endif + +#ifndef O_SYNC +# define O_SYNC 0 +#endif + +/* For systems that distinguish between text and binary I/O. + O_BINARY is usually declared in fcntl.h */ +#if !defined O_BINARY && defined _O_BINARY + /* For MSC-compatible compilers. */ +# define O_BINARY _O_BINARY +# define O_TEXT _O_TEXT +#endif + +#ifdef __BEOS__ + /* BeOS 5 has O_BINARY and O_TEXT, but they have no effect. */ +# undef O_BINARY +# undef O_TEXT +#endif + +#ifndef O_BINARY +# define O_BINARY 0 +# define O_TEXT 0 +#endif + + +#endif /* _GL_FCNTL_H */ +#endif /* _GL_FCNTL_H */ diff --git a/src/bin/findutils/gnulib/lib/fd-safer.c b/src/bin/findutils/gnulib/lib/fd-safer.c new file mode 100644 index 0000000000..df38c8f7e8 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fd-safer.c @@ -0,0 +1,56 @@ +/* Return a safer copy of a file descriptor. + + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert. */ + +#include + +#include "unistd-safer.h" + +#include + +#include +#ifndef STDIN_FILENO +# define STDIN_FILENO 0 +#endif +#ifndef STDERR_FILENO +# define STDERR_FILENO 2 +#endif + +/* Return FD, unless FD would be a copy of standard input, output, or + error; in that case, return a duplicate of FD, closing FD. On + failure to duplicate, close FD, set errno, and return -1. Preserve + errno if FD is negative, so that the caller can always inspect + errno when the returned value is negative. + + This function is usefully wrapped around functions that return file + descriptors, e.g., fd_safer (open ("file", O_RDONLY)). */ + +int +fd_safer (int fd) +{ + if (STDIN_FILENO <= fd && fd <= STDERR_FILENO) + { + int f = dup_safer (fd); + int e = errno; + close (fd); + errno = e; + fd = f; + } + + return fd; +} diff --git a/src/bin/findutils/gnulib/lib/fflush.c b/src/bin/findutils/gnulib/lib/fflush.c new file mode 100644 index 0000000000..be97769a4a --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fflush.c @@ -0,0 +1,109 @@ +/* fflush.c -- allow flushing input streams + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Eric Blake. */ + +#include + +/* Specification. */ +#include + +#include +#include + +#include "freading.h" +#include "fpurge.h" + +#undef fflush + +/* Flush all pending data on STREAM according to POSIX rules. Both + output and seekable input streams are supported. */ +int +rpl_fflush (FILE *stream) +{ + int result; + off_t pos; + + /* When stream is NULL, POSIX and C99 only require flushing of "output + streams and update streams in which the most recent operation was not + input", and all implementations do this. + + When stream is "an output stream or an update stream in which the most + recent operation was not input", POSIX and C99 requires that fflush + writes out any buffered data, and all implementations do this. + + When stream is, however, an input stream or an update stream in + which the most recent operation was input, C99 specifies nothing, + and POSIX only specifies behavior if the stream is seekable. + mingw, in particular, drops the input buffer, leaving the file + descriptor positioned at the end of the input buffer. I.e. ftell + (stream) is lost. We don't want to call the implementation's + fflush in this case. + + We test ! freading (stream) here, rather than fwriting (stream), because + what we need to know is whether the stream holds a "read buffer", and on + mingw this is indicated by _IOREAD, regardless of _IOWRT. */ + if (stream == NULL || ! freading (stream)) + return fflush (stream); + + /* POSIX does not specify fflush behavior for non-seekable input + streams. Some implementations purge unread data, some return + EBADF, some do nothing. */ + pos = ftello (stream); + if (pos == -1) + { + errno = EBADF; + return EOF; + } + + /* To get here, we must be flushing a seekable input stream, so the + semantics of fpurge are now appropriate to clear the buffer. To + avoid losing data, the lseek is also necessary. */ + result = fpurge (stream); + if (result != 0) + return result; + +#if defined __sferror && defined __SNPT /* FreeBSD, NetBSD, OpenBSD, MacOS X, Cygwin */ + + { + /* Disable seek optimization for the next fseeko call. This tells the + following fseeko call to seek to the desired position directly, rather + than to seek to a block-aligned boundary. */ + int saved_flags = stream->_flags & (__SOPT | __SNPT); + stream->_flags = (stream->_flags & ~__SOPT) | __SNPT; + + result = fseeko (stream, pos, SEEK_SET); + + stream->_flags = (stream->_flags & ~(__SOPT | __SNPT)) | saved_flags; + } + return result; + +#else + + pos = lseek (fileno (stream), pos, SEEK_SET); + if (pos == -1) + return EOF; + /* After a successful lseek, update the file descriptor's position cache + in the stream. */ +# if defined __sferror /* FreeBSD, NetBSD, OpenBSD, MacOS X, Cygwin */ + stream->_offset = pos; + stream->_flags |= __SOFF; +# endif + + return 0; + +#endif +} diff --git a/src/bin/findutils/gnulib/lib/file-set.c b/src/bin/findutils/gnulib/lib/file-set.c new file mode 100644 index 0000000000..46dcf5fbb4 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/file-set.c @@ -0,0 +1,74 @@ +/* Specialized functions to manipulate a set of files. + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include +#include "file-set.h" + +#include "hash-triple.h" +#include "xalloc.h" + +/* Record file, FILE, and dev/ino from *STATS, in the hash table, HT. + If HT is NULL, return immediately. + If memory allocation fails, exit immediately. */ +void +record_file (Hash_table *ht, char const *file, struct stat const *stats) +{ + struct F_triple *ent; + + if (ht == NULL) + return; + + ent = xmalloc (sizeof *ent); + ent->name = xstrdup (file); + ent->st_ino = stats->st_ino; + ent->st_dev = stats->st_dev; + + { + struct F_triple *ent_from_table = hash_insert (ht, ent); + if (ent_from_table == NULL) + { + /* Insertion failed due to lack of memory. */ + xalloc_die (); + } + + if (ent_from_table != ent) + { + /* There was alread a matching entry in the table, so ENT was + not inserted. Free it. */ + triple_free (ent); + } + } +} + +/* Return true if there is an entry in hash table, HT, + for the file described by FILE and STATS. */ +bool +seen_file (Hash_table const *ht, char const *file, + struct stat const *stats) +{ + struct F_triple new_ent; + + if (ht == NULL) + return false; + + new_ent.name = (char *) file; + new_ent.st_ino = stats->st_ino; + new_ent.st_dev = stats->st_dev; + + return !!hash_lookup (ht, &new_ent); +} diff --git a/src/bin/findutils/gnulib/lib/file-set.h b/src/bin/findutils/gnulib/lib/file-set.h new file mode 100644 index 0000000000..a5a159e94d --- /dev/null +++ b/src/bin/findutils/gnulib/lib/file-set.h @@ -0,0 +1,12 @@ +#include +#include +#include + +#include "hash.h" + +extern void record_file (Hash_table *ht, char const *file, + struct stat const *stats) + __attribute__((nonnull(2, 3))); + +extern bool seen_file (Hash_table const *ht, char const *file, + struct stat const *stats); diff --git a/src/bin/findutils/lib/fileblocks.c b/src/bin/findutils/gnulib/lib/fileblocks.c similarity index 52% rename from src/bin/findutils/lib/fileblocks.c rename to src/bin/findutils/gnulib/lib/fileblocks.c index 83ac04fd6e..822935af93 100644 --- a/src/bin/findutils/lib/fileblocks.c +++ b/src/bin/findutils/gnulib/lib/fileblocks.c @@ -1,10 +1,12 @@ /* Convert file size to number of blocks on System V-like machines. - Copyright (C) 1990 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + Copyright (C) 1990, 1997, 1998, 1999, 2004, 2005, 2006 Free Software + Foundation, Inc. + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -12,41 +14,43 @@ GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . */ /* Written by Brian L. Matthews, blm@6sceng.UUCP. */ - -#ifdef HAVE_CONFIG_H + #include -#endif -#if !defined (HAVE_ST_BLOCKS) && !defined(_POSIX_SOURCE) #include -#include -#ifndef NINDIR -/* Some SysV's, like Irix, seem to lack these. Hope they're correct. */ -/* Size of a indirect block, in bytes. */ -#ifndef BSIZE -#define BSIZE 1024 +#if HAVE_SYS_PARAM_H +# include #endif +#if !HAVE_STRUCT_STAT_ST_BLOCKS && !defined _POSIX_SOURCE && defined BSIZE + +# include + +# ifndef NINDIR + +# if defined __DJGPP__ +typedef long daddr_t; /* for disk address */ +# endif + +/* Some SysV's, like Irix, seem to lack this. Hope it's correct. */ /* Number of inode pointers per indirect block. */ -#define NINDIR (BSIZE/sizeof(daddr_t)) -#endif /* !NINDIR */ +# define NINDIR (BSIZE / sizeof (daddr_t)) +# endif /* !NINDIR */ /* Number of direct block addresses in an inode. */ -#define NDIR 10 +# define NDIR 10 /* Return the number of 512-byte blocks in a file of SIZE bytes. */ -long -st_blocks (size) - long size; +off_t +st_blocks (off_t size) { - long datablks = (size + 512 - 1) / 512; - long indrblks = 0; + off_t datablks = size / 512 + (size % 512 != 0); + off_t indrblks = 0; if (datablks > NDIR) { @@ -63,4 +67,8 @@ st_blocks (size) return datablks + indrblks; } +#else +/* This declaration is solely to ensure that after preprocessing + this file is never empty. */ +typedef int textutils_fileblocks_unused; #endif diff --git a/src/bin/findutils/gnulib/lib/filemode.c b/src/bin/findutils/gnulib/lib/filemode.c new file mode 100644 index 0000000000..ac62bfc6ef --- /dev/null +++ b/src/bin/findutils/gnulib/lib/filemode.c @@ -0,0 +1,180 @@ +/* filemode.c -- make a string describing file modes + + Copyright (C) 1985, 1990, 1993, 1998-2000, 2004, 2006 Free Software + Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "filemode.h" + +/* The following is for Cray DMF (Data Migration Facility), which is a + HSM file system. A migrated file has a `st_dm_mode' that is + different from the normal `st_mode', so any tests for migrated + files should use the former. */ +#if HAVE_ST_DM_MODE +# define IS_MIGRATED_FILE(statp) \ + (S_ISOFD (statp->st_dm_mode) || S_ISOFL (statp->st_dm_mode)) +#else +# define IS_MIGRATED_FILE(statp) 0 +#endif + +#if ! HAVE_DECL_STRMODE + +/* Return a character indicating the type of file described by + file mode BITS: + '-' regular file + 'b' block special file + 'c' character special file + 'C' high performance ("contiguous data") file + 'd' directory + 'D' door + 'l' symbolic link + 'm' multiplexed file (7th edition Unix; obsolete) + 'n' network special file (HP-UX) + 'p' fifo (named pipe) + 'P' port + 's' socket + 'w' whiteout (4.4BSD) + '?' some other file type */ + +static char +ftypelet (mode_t bits) +{ + /* These are the most common, so test for them first. */ + if (S_ISREG (bits)) + return '-'; + if (S_ISDIR (bits)) + return 'd'; + + /* Other letters standardized by POSIX 1003.1-2004. */ + if (S_ISBLK (bits)) + return 'b'; + if (S_ISCHR (bits)) + return 'c'; + if (S_ISLNK (bits)) + return 'l'; + if (S_ISFIFO (bits)) + return 'p'; + + /* Other file types (though not letters) standardized by POSIX. */ + if (S_ISSOCK (bits)) + return 's'; + + /* Nonstandard file types. */ + if (S_ISCTG (bits)) + return 'C'; + if (S_ISDOOR (bits)) + return 'D'; + if (S_ISMPB (bits) || S_ISMPC (bits)) + return 'm'; + if (S_ISNWK (bits)) + return 'n'; + if (S_ISPORT (bits)) + return 'P'; + if (S_ISWHT (bits)) + return 'w'; + + return '?'; +} + +/* Like filemodestring, but rely only on MODE. */ + +void +strmode (mode_t mode, char *str) +{ + str[0] = ftypelet (mode); + str[1] = mode & S_IRUSR ? 'r' : '-'; + str[2] = mode & S_IWUSR ? 'w' : '-'; + str[3] = (mode & S_ISUID + ? (mode & S_IXUSR ? 's' : 'S') + : (mode & S_IXUSR ? 'x' : '-')); + str[4] = mode & S_IRGRP ? 'r' : '-'; + str[5] = mode & S_IWGRP ? 'w' : '-'; + str[6] = (mode & S_ISGID + ? (mode & S_IXGRP ? 's' : 'S') + : (mode & S_IXGRP ? 'x' : '-')); + str[7] = mode & S_IROTH ? 'r' : '-'; + str[8] = mode & S_IWOTH ? 'w' : '-'; + str[9] = (mode & S_ISVTX + ? (mode & S_IXOTH ? 't' : 'T') + : (mode & S_IXOTH ? 'x' : '-')); + str[10] = ' '; + str[11] = '\0'; +} + +#endif /* ! HAVE_DECL_STRMODE */ + +/* filemodestring - fill in string STR with an ls-style ASCII + representation of the st_mode field of file stats block STATP. + 12 characters are stored in STR. + The characters stored in STR are: + + 0 File type, as in ftypelet above, except that other letters are used + for files whose type cannot be determined solely from st_mode: + + 'F' semaphore + 'M' migrated file (Cray DMF) + 'Q' message queue + 'S' shared memory object + 'T' typed memory object + + 1 'r' if the owner may read, '-' otherwise. + + 2 'w' if the owner may write, '-' otherwise. + + 3 'x' if the owner may execute, 's' if the file is + set-user-id, '-' otherwise. + 'S' if the file is set-user-id, but the execute + bit isn't set. + + 4 'r' if group members may read, '-' otherwise. + + 5 'w' if group members may write, '-' otherwise. + + 6 'x' if group members may execute, 's' if the file is + set-group-id, '-' otherwise. + 'S' if it is set-group-id but not executable. + + 7 'r' if any user may read, '-' otherwise. + + 8 'w' if any user may write, '-' otherwise. + + 9 'x' if any user may execute, 't' if the file is "sticky" + (will be retained in swap space after execution), '-' + otherwise. + 'T' if the file is sticky but not executable. + + 10 ' ' for compatibility with 4.4BSD strmode, + since this interface does not support ACLs. + + 11 '\0'. */ + +void +filemodestring (struct stat const *statp, char *str) +{ + strmode (statp->st_mode, str); + + if (S_TYPEISSEM (statp)) + str[0] = 'F'; + else if (IS_MIGRATED_FILE (statp)) + str[0] = 'M'; + else if (S_TYPEISMQ (statp)) + str[0] = 'Q'; + else if (S_TYPEISSHM (statp)) + str[0] = 'S'; + else if (S_TYPEISTMO (statp)) + str[0] = 'T'; +} diff --git a/src/bin/findutils/gnulib/lib/filemode.h b/src/bin/findutils/gnulib/lib/filemode.h new file mode 100644 index 0000000000..29deecdc75 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/filemode.h @@ -0,0 +1,32 @@ +/* Make a string describing file modes. + + Copyright (C) 1998, 1999, 2003, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef FILEMODE_H_ + +# include +# include + +# if HAVE_DECL_STRMODE +# include /* FreeBSD, OpenBSD */ +# include /* NetBSD */ +# else +void strmode (mode_t mode, char *str); +# endif + +void filemodestring (struct stat const *statp, char *str); + +#endif diff --git a/src/bin/findutils/gnulib/lib/filenamecat.c b/src/bin/findutils/gnulib/lib/filenamecat.c new file mode 100644 index 0000000000..ef46de209a --- /dev/null +++ b/src/bin/findutils/gnulib/lib/filenamecat.c @@ -0,0 +1,102 @@ +/* Concatenate two arbitrary file names. + + Copyright (C) 1996-2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Jim Meyering. */ + +#include + +/* Specification. */ +#include "filenamecat.h" + +#include +#include + +#include "dirname.h" +#include "xalloc.h" + +#if ! HAVE_MEMPCPY && ! defined mempcpy +# define mempcpy(D, S, N) ((void *) ((char *) memcpy (D, S, N) + (N))) +#endif + +/* Return the longest suffix of F that is a relative file name. + If it has no such suffix, return the empty string. */ + +static char const * +longest_relative_suffix (char const *f) +{ + for (f += FILE_SYSTEM_PREFIX_LEN (f); ISSLASH (*f); f++) + continue; + return f; +} + +/* Concatenate two file name components, DIR and ABASE, in + newly-allocated storage and return the result. + The resulting file name F is such that the commands "ls F" and "(cd + DIR; ls BASE)" refer to the same file, where BASE is ABASE with any + file system prefixes and leading separators removed. + Arrange for a directory separator if necessary between DIR and BASE + in the result, removing any redundant separators. + In any case, if BASE_IN_RESULT is non-NULL, set + *BASE_IN_RESULT to point to the copy of ABASE in the returned + concatenation. However, if ABASE begins with more than one slash, + set *BASE_IN_RESULT to point to the sole corresponding slash that + is copied into the result buffer. + + Return NULL if malloc fails. */ + +char * +mfile_name_concat (char const *dir, char const *abase, char **base_in_result) +{ + char const *dirbase = last_component (dir); + size_t dirbaselen = base_len (dirbase); + size_t dirlen = dirbase - dir + dirbaselen; + size_t needs_separator = (dirbaselen && ! ISSLASH (dirbase[dirbaselen - 1])); + + char const *base = longest_relative_suffix (abase); + size_t baselen = strlen (base); + + char *p_concat = malloc (dirlen + needs_separator + baselen + 1); + char *p; + + if (p_concat == NULL) + return NULL; + + p = mempcpy (p_concat, dir, dirlen); + *p = DIRECTORY_SEPARATOR; + p += needs_separator; + + if (base_in_result) + *base_in_result = p - IS_ABSOLUTE_FILE_NAME (abase); + + p = mempcpy (p, base, baselen); + *p = '\0'; + + return p_concat; +} + +/* Just like mfile_name_concat, above, except, rather than + returning NULL upon malloc failure, here, we report the + "memory exhausted" condition and exit. */ + +char * +file_name_concat (char const *dir, char const *abase, char **base_in_result) +{ + char *p = mfile_name_concat (dir, abase, base_in_result); + if (p == NULL) + xalloc_die (); + return p; +} diff --git a/src/bin/findutils/gnulib/lib/filenamecat.h b/src/bin/findutils/gnulib/lib/filenamecat.h new file mode 100644 index 0000000000..334c887c77 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/filenamecat.h @@ -0,0 +1,24 @@ +/* Concatenate two arbitrary file names. + + Copyright (C) 1996, 1997, 2003, 2005, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Jim Meyering. */ + +char *file_name_concat (char const *dir, char const *base, + char **base_in_result); + +char *mfile_name_concat (char const *dir, char const *base, + char **base_in_result); diff --git a/src/bin/findutils/gnulib/lib/fnmatch.c b/src/bin/findutils/gnulib/lib/fnmatch.c new file mode 100644 index 0000000000..676e1bd8b3 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fnmatch.c @@ -0,0 +1,354 @@ +/* Copyright (C) 1991,1992,1993,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007 + Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _LIBC +# include +#endif + +/* Enable GNU extensions in fnmatch.h. */ +#ifndef _GNU_SOURCE +# define _GNU_SOURCE 1 +#endif + +#if ! defined __builtin_expect && __GNUC__ < 3 +# define __builtin_expect(expr, expected) (expr) +#endif + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#define WIDE_CHAR_SUPPORT \ + (HAVE_WCTYPE_H && HAVE_BTOWC && HAVE_ISWCTYPE \ + && HAVE_WMEMCHR && (HAVE_WMEMCPY || HAVE_WMEMPCPY)) + +/* For platform which support the ISO C amendement 1 functionality we + support user defined character classes. */ +#if defined _LIBC || WIDE_CHAR_SUPPORT +# include +# include +#endif + +/* We need some of the locale data (the collation sequence information) + but there is no interface to get this information in general. Therefore + we support a correct implementation only in glibc. */ +#ifdef _LIBC +# include "../locale/localeinfo.h" +# include "../locale/elem-hash.h" +# include "../locale/coll-lookup.h" +# include + +# define CONCAT(a,b) __CONCAT(a,b) +# define mbsrtowcs __mbsrtowcs +# define fnmatch __fnmatch +extern int fnmatch (const char *pattern, const char *string, int flags); +#endif + +#ifndef SIZE_MAX +# define SIZE_MAX ((size_t) -1) +#endif + +/* We often have to test for FNM_FILE_NAME and FNM_PERIOD being both set. */ +#define NO_LEADING_PERIOD(flags) \ + ((flags & (FNM_FILE_NAME | FNM_PERIOD)) == (FNM_FILE_NAME | FNM_PERIOD)) + +/* Comment out all this code if we are using the GNU C Library, and are not + actually compiling the library itself, and have not detected a bug + in the library. This code is part of the GNU C + Library, but also included in many other GNU distributions. Compiling + and linking in this code is a waste when using the GNU C library + (especially if it is a shared library). Rather than having every GNU + program understand `configure --with-gnu-libc' and omit the object files, + it is simpler to just do this in the source for each such file. */ + +#if defined _LIBC || !defined __GNU_LIBRARY__ || !HAVE_FNMATCH_GNU + + +# if ! (defined isblank || (HAVE_ISBLANK && HAVE_DECL_ISBLANK)) +# define isblank(c) ((c) == ' ' || (c) == '\t') +# endif + +# define STREQ(s1, s2) ((strcmp (s1, s2) == 0)) + +# if defined _LIBC || WIDE_CHAR_SUPPORT +/* The GNU C library provides support for user-defined character classes + and the functions from ISO C amendement 1. */ +# ifdef CHARCLASS_NAME_MAX +# define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX +# else +/* This shouldn't happen but some implementation might still have this + problem. Use a reasonable default value. */ +# define CHAR_CLASS_MAX_LENGTH 256 +# endif + +# ifdef _LIBC +# define IS_CHAR_CLASS(string) __wctype (string) +# else +# define IS_CHAR_CLASS(string) wctype (string) +# endif + +# ifdef _LIBC +# define ISWCTYPE(WC, WT) __iswctype (WC, WT) +# else +# define ISWCTYPE(WC, WT) iswctype (WC, WT) +# endif + +# if (HAVE_MBSTATE_T && HAVE_MBSRTOWCS) || _LIBC +/* In this case we are implementing the multibyte character handling. */ +# define HANDLE_MULTIBYTE 1 +# endif + +# else +# define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */ + +# define IS_CHAR_CLASS(string) \ + (STREQ (string, "alpha") || STREQ (string, "upper") \ + || STREQ (string, "lower") || STREQ (string, "digit") \ + || STREQ (string, "alnum") || STREQ (string, "xdigit") \ + || STREQ (string, "space") || STREQ (string, "print") \ + || STREQ (string, "punct") || STREQ (string, "graph") \ + || STREQ (string, "cntrl") || STREQ (string, "blank")) +# endif + +/* Avoid depending on library functions or files + whose names are inconsistent. */ + +/* Global variable. */ +static int posixly_correct; + +# ifndef internal_function +/* Inside GNU libc we mark some function in a special way. In other + environments simply ignore the marking. */ +# define internal_function +# endif + +/* Note that this evaluates C many times. */ +# define FOLD(c) ((flags & FNM_CASEFOLD) ? tolower (c) : (c)) +# define CHAR char +# define UCHAR unsigned char +# define INT int +# define FCT internal_fnmatch +# define EXT ext_match +# define END end_pattern +# define L_(CS) CS +# ifdef _LIBC +# define BTOWC(C) __btowc (C) +# else +# define BTOWC(C) btowc (C) +# endif +# define STRLEN(S) strlen (S) +# define STRCAT(D, S) strcat (D, S) +# ifdef _LIBC +# define MEMPCPY(D, S, N) __mempcpy (D, S, N) +# else +# if HAVE_MEMPCPY +# define MEMPCPY(D, S, N) mempcpy (D, S, N) +# else +# define MEMPCPY(D, S, N) ((void *) ((char *) memcpy (D, S, N) + (N))) +# endif +# endif +# define MEMCHR(S, C, N) memchr (S, C, N) +# define STRCOLL(S1, S2) strcoll (S1, S2) +# include "fnmatch_loop.c" + + +# if HANDLE_MULTIBYTE +# define FOLD(c) ((flags & FNM_CASEFOLD) ? towlower (c) : (c)) +# define CHAR wchar_t +# define UCHAR wint_t +# define INT wint_t +# define FCT internal_fnwmatch +# define EXT ext_wmatch +# define END end_wpattern +# define L_(CS) L##CS +# define BTOWC(C) (C) +# ifdef _LIBC +# define STRLEN(S) __wcslen (S) +# define STRCAT(D, S) __wcscat (D, S) +# define MEMPCPY(D, S, N) __wmempcpy (D, S, N) +# else +# define STRLEN(S) wcslen (S) +# define STRCAT(D, S) wcscat (D, S) +# if HAVE_WMEMPCPY +# define MEMPCPY(D, S, N) wmempcpy (D, S, N) +# else +# define MEMPCPY(D, S, N) (wmemcpy (D, S, N) + (N)) +# endif +# endif +# define MEMCHR(S, C, N) wmemchr (S, C, N) +# define STRCOLL(S1, S2) wcscoll (S1, S2) +# define WIDE_CHAR_VERSION 1 + +# undef IS_CHAR_CLASS +/* We have to convert the wide character string in a multibyte string. But + we know that the character class names consist of alphanumeric characters + from the portable character set, and since the wide character encoding + for a member of the portable character set is the same code point as + its single-byte encoding, we can use a simplified method to convert the + string to a multibyte character string. */ +static wctype_t +is_char_class (const wchar_t *wcs) +{ + char s[CHAR_CLASS_MAX_LENGTH + 1]; + char *cp = s; + + do + { + /* Test for a printable character from the portable character set. */ +# ifdef _LIBC + if (*wcs < 0x20 || *wcs > 0x7e + || *wcs == 0x24 || *wcs == 0x40 || *wcs == 0x60) + return (wctype_t) 0; +# else + switch (*wcs) + { + case L' ': case L'!': case L'"': case L'#': case L'%': + case L'&': case L'\'': case L'(': case L')': case L'*': + case L'+': case L',': case L'-': case L'.': case L'/': + case L'0': case L'1': case L'2': case L'3': case L'4': + case L'5': case L'6': case L'7': case L'8': case L'9': + case L':': case L';': case L'<': case L'=': case L'>': + case L'?': + case L'A': case L'B': case L'C': case L'D': case L'E': + case L'F': case L'G': case L'H': case L'I': case L'J': + case L'K': case L'L': case L'M': case L'N': case L'O': + case L'P': case L'Q': case L'R': case L'S': case L'T': + case L'U': case L'V': case L'W': case L'X': case L'Y': + case L'Z': + case L'[': case L'\\': case L']': case L'^': case L'_': + case L'a': case L'b': case L'c': case L'd': case L'e': + case L'f': case L'g': case L'h': case L'i': case L'j': + case L'k': case L'l': case L'm': case L'n': case L'o': + case L'p': case L'q': case L'r': case L's': case L't': + case L'u': case L'v': case L'w': case L'x': case L'y': + case L'z': case L'{': case L'|': case L'}': case L'~': + break; + default: + return (wctype_t) 0; + } +# endif + + /* Avoid overrunning the buffer. */ + if (cp == s + CHAR_CLASS_MAX_LENGTH) + return (wctype_t) 0; + + *cp++ = (char) *wcs++; + } + while (*wcs != L'\0'); + + *cp = '\0'; + +# ifdef _LIBC + return __wctype (s); +# else + return wctype (s); +# endif +} +# define IS_CHAR_CLASS(string) is_char_class (string) + +# include "fnmatch_loop.c" +# endif + + +int +fnmatch (const char *pattern, const char *string, int flags) +{ +# if HANDLE_MULTIBYTE +# define ALLOCA_LIMIT 2000 + if (__builtin_expect (MB_CUR_MAX, 1) != 1) + { + mbstate_t ps; + size_t patsize; + size_t strsize; + size_t totsize; + wchar_t *wpattern; + wchar_t *wstring; + int res; + + /* Calculate the size needed to convert the strings to + wide characters. */ + memset (&ps, '\0', sizeof (ps)); + patsize = mbsrtowcs (NULL, &pattern, 0, &ps) + 1; + if (__builtin_expect (patsize != 0, 1)) + { + assert (mbsinit (&ps)); + strsize = mbsrtowcs (NULL, &string, 0, &ps) + 1; + if (__builtin_expect (strsize != 0, 1)) + { + assert (mbsinit (&ps)); + totsize = patsize + strsize; + if (__builtin_expect (! (patsize <= totsize + && totsize <= SIZE_MAX / sizeof (wchar_t)), + 0)) + { + errno = ENOMEM; + return -1; + } + + /* Allocate room for the wide characters. */ + if (__builtin_expect (totsize < ALLOCA_LIMIT, 1)) + wpattern = (wchar_t *) alloca (totsize * sizeof (wchar_t)); + else + { + wpattern = malloc (totsize * sizeof (wchar_t)); + if (__builtin_expect (! wpattern, 0)) + { + errno = ENOMEM; + return -1; + } + } + wstring = wpattern + patsize; + + /* Convert the strings into wide characters. */ + mbsrtowcs (wpattern, &pattern, patsize, &ps); + assert (mbsinit (&ps)); + mbsrtowcs (wstring, &string, strsize, &ps); + + res = internal_fnwmatch (wpattern, wstring, wstring + strsize - 1, + flags & FNM_PERIOD, flags); + + if (__builtin_expect (! (totsize < ALLOCA_LIMIT), 0)) + free (wpattern); + return res; + } + } + } + +# endif /* HANDLE_MULTIBYTE */ + + return internal_fnmatch (pattern, string, string + strlen (string), + flags & FNM_PERIOD, flags); +} + +# ifdef _LIBC +# undef fnmatch +versioned_symbol (libc, __fnmatch, fnmatch, GLIBC_2_2_3); +# if SHLIB_COMPAT(libc, GLIBC_2_0, GLIBC_2_2_3) +strong_alias (__fnmatch, __fnmatch_old) +compat_symbol (libc, __fnmatch_old, fnmatch, GLIBC_2_0); +# endif +libc_hidden_ver (__fnmatch, fnmatch) +# endif + +#endif /* _LIBC or not __GNU_LIBRARY__. */ diff --git a/src/bin/findutils/gnulib/lib/fnmatch.h b/src/bin/findutils/gnulib/lib/fnmatch.h new file mode 100644 index 0000000000..8b38f3a7e8 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fnmatch.h @@ -0,0 +1,66 @@ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +/* Copyright (C) 1991, 1992, 1993, 1996, 1997, 1998, 1999, 2001, 2002, 2003, + 2005, 2007 Free Software Foundation, Inc. + + This file is part of the GNU C Library. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _FNMATCH_H +#define _FNMATCH_H 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* We #undef these before defining them because some losing systems + (HP-UX A.08.07 for example) define these in . */ +#undef FNM_PATHNAME +#undef FNM_NOESCAPE +#undef FNM_PERIOD + +/* Bits set in the FLAGS argument to `fnmatch'. */ +#define FNM_PATHNAME (1 << 0) /* No wildcard can ever match `/'. */ +#define FNM_NOESCAPE (1 << 1) /* Backslashes don't quote special chars. */ +#define FNM_PERIOD (1 << 2) /* Leading `.' is matched only explicitly. */ + +#if !defined _POSIX_C_SOURCE || _POSIX_C_SOURCE < 2 || defined _GNU_SOURCE +# define FNM_FILE_NAME FNM_PATHNAME /* Preferred GNU name. */ +# define FNM_LEADING_DIR (1 << 3) /* Ignore `/...' after a match. */ +# define FNM_CASEFOLD (1 << 4) /* Compare without regard to case. */ +# define FNM_EXTMATCH (1 << 5) /* Use ksh-like extended matching. */ +#endif + +/* Value returned by `fnmatch' if STRING does not match PATTERN. */ +#define FNM_NOMATCH 1 + +/* This value is returned if the implementation does not support + `fnmatch'. Since this is not the case here it will never be + returned but the conformance test suites still require the symbol + to be defined. */ +#ifdef _XOPEN_SOURCE +# define FNM_NOSYS (-1) +#endif + +/* Match NAME against the file name pattern PATTERN, + returning zero if it matches, FNM_NOMATCH if not. */ +extern int fnmatch (const char *__pattern, const char *__name, + int __flags); + +#ifdef __cplusplus +} +#endif + +#endif /* fnmatch.h */ diff --git a/src/bin/findutils/gnulib/lib/fnmatch.in.h b/src/bin/findutils/gnulib/lib/fnmatch.in.h new file mode 100644 index 0000000000..3518c298ec --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fnmatch.in.h @@ -0,0 +1,65 @@ +/* Copyright (C) 1991, 1992, 1993, 1996, 1997, 1998, 1999, 2001, 2002, 2003, + 2005, 2007 Free Software Foundation, Inc. + + This file is part of the GNU C Library. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _FNMATCH_H +#define _FNMATCH_H 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* We #undef these before defining them because some losing systems + (HP-UX A.08.07 for example) define these in . */ +#undef FNM_PATHNAME +#undef FNM_NOESCAPE +#undef FNM_PERIOD + +/* Bits set in the FLAGS argument to `fnmatch'. */ +#define FNM_PATHNAME (1 << 0) /* No wildcard can ever match `/'. */ +#define FNM_NOESCAPE (1 << 1) /* Backslashes don't quote special chars. */ +#define FNM_PERIOD (1 << 2) /* Leading `.' is matched only explicitly. */ + +#if !defined _POSIX_C_SOURCE || _POSIX_C_SOURCE < 2 || defined _GNU_SOURCE +# define FNM_FILE_NAME FNM_PATHNAME /* Preferred GNU name. */ +# define FNM_LEADING_DIR (1 << 3) /* Ignore `/...' after a match. */ +# define FNM_CASEFOLD (1 << 4) /* Compare without regard to case. */ +# define FNM_EXTMATCH (1 << 5) /* Use ksh-like extended matching. */ +#endif + +/* Value returned by `fnmatch' if STRING does not match PATTERN. */ +#define FNM_NOMATCH 1 + +/* This value is returned if the implementation does not support + `fnmatch'. Since this is not the case here it will never be + returned but the conformance test suites still require the symbol + to be defined. */ +#ifdef _XOPEN_SOURCE +# define FNM_NOSYS (-1) +#endif + +/* Match NAME against the file name pattern PATTERN, + returning zero if it matches, FNM_NOMATCH if not. */ +extern int fnmatch (const char *__pattern, const char *__name, + int __flags); + +#ifdef __cplusplus +} +#endif + +#endif /* fnmatch.h */ diff --git a/src/bin/findutils/gnulib/lib/fnmatch_loop.c b/src/bin/findutils/gnulib/lib/fnmatch_loop.c new file mode 100644 index 0000000000..337fba9d8e --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fnmatch_loop.c @@ -0,0 +1,1210 @@ +/* Copyright (C) 1991,1992,1993,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006 + Free Software Foundation, Inc. + This file is part of the GNU C Library. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* Match STRING against the file name pattern PATTERN, returning zero if + it matches, nonzero if not. */ +static int EXT (INT opt, const CHAR *pattern, const CHAR *string, + const CHAR *string_end, bool no_leading_period, int flags) + internal_function; +static const CHAR *END (const CHAR *patternp) internal_function; + +static int +internal_function +FCT (const CHAR *pattern, const CHAR *string, const CHAR *string_end, + bool no_leading_period, int flags) +{ + register const CHAR *p = pattern, *n = string; + register UCHAR c; +#ifdef _LIBC +# if WIDE_CHAR_VERSION + const char *collseq = (const char *) + _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC); +# else + const UCHAR *collseq = (const UCHAR *) + _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQMB); +# endif +#endif + + while ((c = *p++) != L_('\0')) + { + bool new_no_leading_period = false; + c = FOLD (c); + + switch (c) + { + case L_('?'): + if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(') + { + int res; + + res = EXT (c, p, n, string_end, no_leading_period, + flags); + if (res != -1) + return res; + } + + if (n == string_end) + return FNM_NOMATCH; + else if (*n == L_('/') && (flags & FNM_FILE_NAME)) + return FNM_NOMATCH; + else if (*n == L_('.') && no_leading_period) + return FNM_NOMATCH; + break; + + case L_('\\'): + if (!(flags & FNM_NOESCAPE)) + { + c = *p++; + if (c == L_('\0')) + /* Trailing \ loses. */ + return FNM_NOMATCH; + c = FOLD (c); + } + if (n == string_end || FOLD ((UCHAR) *n) != c) + return FNM_NOMATCH; + break; + + case L_('*'): + if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(') + { + int res; + + res = EXT (c, p, n, string_end, no_leading_period, + flags); + if (res != -1) + return res; + } + + if (n != string_end && *n == L_('.') && no_leading_period) + return FNM_NOMATCH; + + for (c = *p++; c == L_('?') || c == L_('*'); c = *p++) + { + if (*p == L_('(') && (flags & FNM_EXTMATCH) != 0) + { + const CHAR *endp = END (p); + if (endp != p) + { + /* This is a pattern. Skip over it. */ + p = endp; + continue; + } + } + + if (c == L_('?')) + { + /* A ? needs to match one character. */ + if (n == string_end) + /* There isn't another character; no match. */ + return FNM_NOMATCH; + else if (*n == L_('/') + && __builtin_expect (flags & FNM_FILE_NAME, 0)) + /* A slash does not match a wildcard under + FNM_FILE_NAME. */ + return FNM_NOMATCH; + else + /* One character of the string is consumed in matching + this ? wildcard, so *??? won't match if there are + less than three characters. */ + ++n; + } + } + + if (c == L_('\0')) + /* The wildcard(s) is/are the last element of the pattern. + If the name is a file name and contains another slash + this means it cannot match, unless the FNM_LEADING_DIR + flag is set. */ + { + int result = (flags & FNM_FILE_NAME) == 0 ? 0 : FNM_NOMATCH; + + if (flags & FNM_FILE_NAME) + { + if (flags & FNM_LEADING_DIR) + result = 0; + else + { + if (MEMCHR (n, L_('/'), string_end - n) == NULL) + result = 0; + } + } + + return result; + } + else + { + const CHAR *endp; + + endp = MEMCHR (n, (flags & FNM_FILE_NAME) ? L_('/') : L_('\0'), + string_end - n); + if (endp == NULL) + endp = string_end; + + if (c == L_('[') + || (__builtin_expect (flags & FNM_EXTMATCH, 0) != 0 + && (c == L_('@') || c == L_('+') || c == L_('!')) + && *p == L_('('))) + { + int flags2 = ((flags & FNM_FILE_NAME) + ? flags : (flags & ~FNM_PERIOD)); + bool no_leading_period2 = no_leading_period; + + for (--p; n < endp; ++n, no_leading_period2 = false) + if (FCT (p, n, string_end, no_leading_period2, flags2) + == 0) + return 0; + } + else if (c == L_('/') && (flags & FNM_FILE_NAME)) + { + while (n < string_end && *n != L_('/')) + ++n; + if (n < string_end && *n == L_('/') + && (FCT (p, n + 1, string_end, flags & FNM_PERIOD, flags) + == 0)) + return 0; + } + else + { + int flags2 = ((flags & FNM_FILE_NAME) + ? flags : (flags & ~FNM_PERIOD)); + int no_leading_period2 = no_leading_period; + + if (c == L_('\\') && !(flags & FNM_NOESCAPE)) + c = *p; + c = FOLD (c); + for (--p; n < endp; ++n, no_leading_period2 = false) + if (FOLD ((UCHAR) *n) == c + && (FCT (p, n, string_end, no_leading_period2, flags2) + == 0)) + return 0; + } + } + + /* If we come here no match is possible with the wildcard. */ + return FNM_NOMATCH; + + case L_('['): + { + /* Nonzero if the sense of the character class is inverted. */ + register bool not; + CHAR cold; + UCHAR fn; + + if (posixly_correct == 0) + posixly_correct = getenv ("POSIXLY_CORRECT") != NULL ? 1 : -1; + + if (n == string_end) + return FNM_NOMATCH; + + if (*n == L_('.') && no_leading_period) + return FNM_NOMATCH; + + if (*n == L_('/') && (flags & FNM_FILE_NAME)) + /* `/' cannot be matched. */ + return FNM_NOMATCH; + + not = (*p == L_('!') || (posixly_correct < 0 && *p == L_('^'))); + if (not) + ++p; + + fn = FOLD ((UCHAR) *n); + + c = *p++; + for (;;) + { + if (!(flags & FNM_NOESCAPE) && c == L_('\\')) + { + if (*p == L_('\0')) + return FNM_NOMATCH; + c = FOLD ((UCHAR) *p); + ++p; + + goto normal_bracket; + } + else if (c == L_('[') && *p == L_(':')) + { + /* Leave room for the null. */ + CHAR str[CHAR_CLASS_MAX_LENGTH + 1]; + size_t c1 = 0; +#if defined _LIBC || WIDE_CHAR_SUPPORT + wctype_t wt; +#endif + const CHAR *startp = p; + + for (;;) + { + if (c1 == CHAR_CLASS_MAX_LENGTH) + /* The name is too long and therefore the pattern + is ill-formed. */ + return FNM_NOMATCH; + + c = *++p; + if (c == L_(':') && p[1] == L_(']')) + { + p += 2; + break; + } + if (c < L_('a') || c >= L_('z')) + { + /* This cannot possibly be a character class name. + Match it as a normal range. */ + p = startp; + c = L_('['); + goto normal_bracket; + } + str[c1++] = c; + } + str[c1] = L_('\0'); + +#if defined _LIBC || WIDE_CHAR_SUPPORT + wt = IS_CHAR_CLASS (str); + if (wt == 0) + /* Invalid character class name. */ + return FNM_NOMATCH; + +# if defined _LIBC && ! WIDE_CHAR_VERSION + /* The following code is glibc specific but does + there a good job in speeding up the code since + we can avoid the btowc() call. */ + if (_ISCTYPE ((UCHAR) *n, wt)) + goto matched; +# else + if (ISWCTYPE (BTOWC ((UCHAR) *n), wt)) + goto matched; +# endif +#else + if ((STREQ (str, L_("alnum")) && isalnum ((UCHAR) *n)) + || (STREQ (str, L_("alpha")) && isalpha ((UCHAR) *n)) + || (STREQ (str, L_("blank")) && isblank ((UCHAR) *n)) + || (STREQ (str, L_("cntrl")) && iscntrl ((UCHAR) *n)) + || (STREQ (str, L_("digit")) && isdigit ((UCHAR) *n)) + || (STREQ (str, L_("graph")) && isgraph ((UCHAR) *n)) + || (STREQ (str, L_("lower")) && islower ((UCHAR) *n)) + || (STREQ (str, L_("print")) && isprint ((UCHAR) *n)) + || (STREQ (str, L_("punct")) && ispunct ((UCHAR) *n)) + || (STREQ (str, L_("space")) && isspace ((UCHAR) *n)) + || (STREQ (str, L_("upper")) && isupper ((UCHAR) *n)) + || (STREQ (str, L_("xdigit")) && isxdigit ((UCHAR) *n))) + goto matched; +#endif + c = *p++; + } +#ifdef _LIBC + else if (c == L_('[') && *p == L_('=')) + { + UCHAR str[1]; + uint32_t nrules = + _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES); + const CHAR *startp = p; + + c = *++p; + if (c == L_('\0')) + { + p = startp; + c = L_('['); + goto normal_bracket; + } + str[0] = c; + + c = *++p; + if (c != L_('=') || p[1] != L_(']')) + { + p = startp; + c = L_('['); + goto normal_bracket; + } + p += 2; + + if (nrules == 0) + { + if ((UCHAR) *n == str[0]) + goto matched; + } + else + { + const int32_t *table; +# if WIDE_CHAR_VERSION + const int32_t *weights; + const int32_t *extra; +# else + const unsigned char *weights; + const unsigned char *extra; +# endif + const int32_t *indirect; + int32_t idx; + const UCHAR *cp = (const UCHAR *) str; + + /* This #include defines a local function! */ +# if WIDE_CHAR_VERSION +# include +# else +# include +# endif + +# if WIDE_CHAR_VERSION + table = (const int32_t *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC); + weights = (const int32_t *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC); + extra = (const int32_t *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC); + indirect = (const int32_t *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC); +# else + table = (const int32_t *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB); + weights = (const unsigned char *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB); + extra = (const unsigned char *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB); + indirect = (const int32_t *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB); +# endif + + idx = findidx (&cp); + if (idx != 0) + { + /* We found a table entry. Now see whether the + character we are currently at has the same + equivalance class value. */ + int len = weights[idx]; + int32_t idx2; + const UCHAR *np = (const UCHAR *) n; + + idx2 = findidx (&np); + if (idx2 != 0 && len == weights[idx2]) + { + int cnt = 0; + + while (cnt < len + && (weights[idx + 1 + cnt] + == weights[idx2 + 1 + cnt])) + ++cnt; + + if (cnt == len) + goto matched; + } + } + } + + c = *p++; + } +#endif + else if (c == L_('\0')) + /* [ (unterminated) loses. */ + return FNM_NOMATCH; + else + { + bool is_range = false; + +#ifdef _LIBC + bool is_seqval = false; + + if (c == L_('[') && *p == L_('.')) + { + uint32_t nrules = + _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES); + const CHAR *startp = p; + size_t c1 = 0; + + while (1) + { + c = *++p; + if (c == L_('.') && p[1] == L_(']')) + { + p += 2; + break; + } + if (c == '\0') + return FNM_NOMATCH; + ++c1; + } + + /* We have to handling the symbols differently in + ranges since then the collation sequence is + important. */ + is_range = *p == L_('-') && p[1] != L_('\0'); + + if (nrules == 0) + { + /* There are no names defined in the collation + data. Therefore we only accept the trivial + names consisting of the character itself. */ + if (c1 != 1) + return FNM_NOMATCH; + + if (!is_range && *n == startp[1]) + goto matched; + + cold = startp[1]; + c = *p++; + } + else + { + int32_t table_size; + const int32_t *symb_table; +# ifdef WIDE_CHAR_VERSION + char str[c1]; + size_t strcnt; +# else +# define str (startp + 1) +# endif + const unsigned char *extra; + int32_t idx; + int32_t elem; + int32_t second; + int32_t hash; + +# ifdef WIDE_CHAR_VERSION + /* We have to convert the name to a single-byte + string. This is possible since the names + consist of ASCII characters and the internal + representation is UCS4. */ + for (strcnt = 0; strcnt < c1; ++strcnt) + str[strcnt] = startp[1 + strcnt]; +# endif + + table_size = + _NL_CURRENT_WORD (LC_COLLATE, + _NL_COLLATE_SYMB_HASH_SIZEMB); + symb_table = (const int32_t *) + _NL_CURRENT (LC_COLLATE, + _NL_COLLATE_SYMB_TABLEMB); + extra = (const unsigned char *) + _NL_CURRENT (LC_COLLATE, + _NL_COLLATE_SYMB_EXTRAMB); + + /* Locate the character in the hashing table. */ + hash = elem_hash (str, c1); + + idx = 0; + elem = hash % table_size; + if (symb_table[2 * elem] != 0) + { + second = hash % (table_size - 2) + 1; + + do + { + /* First compare the hashing value. */ + if (symb_table[2 * elem] == hash + && (c1 + == extra[symb_table[2 * elem + 1]]) + && memcmp (str, + &extra[symb_table[2 * elem + + 1] + + 1], c1) == 0) + { + /* Yep, this is the entry. */ + idx = symb_table[2 * elem + 1]; + idx += 1 + extra[idx]; + break; + } + + /* Next entry. */ + elem += second; + } + while (symb_table[2 * elem] != 0); + } + + if (symb_table[2 * elem] != 0) + { + /* Compare the byte sequence but only if + this is not part of a range. */ +# ifdef WIDE_CHAR_VERSION + int32_t *wextra; + + idx += 1 + extra[idx]; + /* Adjust for the alignment. */ + idx = (idx + 3) & ~3; + + wextra = (int32_t *) &extra[idx + 4]; +# endif + + if (! is_range) + { +# ifdef WIDE_CHAR_VERSION + for (c1 = 0; + (int32_t) c1 < wextra[idx]; + ++c1) + if (n[c1] != wextra[1 + c1]) + break; + + if ((int32_t) c1 == wextra[idx]) + goto matched; +# else + for (c1 = 0; c1 < extra[idx]; ++c1) + if (n[c1] != extra[1 + c1]) + break; + + if (c1 == extra[idx]) + goto matched; +# endif + } + + /* Get the collation sequence value. */ + is_seqval = true; +# ifdef WIDE_CHAR_VERSION + cold = wextra[1 + wextra[idx]]; +# else + /* Adjust for the alignment. */ + idx += 1 + extra[idx]; + idx = (idx + 3) & ~4; + cold = *((int32_t *) &extra[idx]); +# endif + + c = *p++; + } + else if (c1 == 1) + { + /* No valid character. Match it as a + single byte. */ + if (!is_range && *n == str[0]) + goto matched; + + cold = str[0]; + c = *p++; + } + else + return FNM_NOMATCH; + } + } + else +# undef str +#endif + { + c = FOLD (c); + normal_bracket: + + /* We have to handling the symbols differently in + ranges since then the collation sequence is + important. */ + is_range = (*p == L_('-') && p[1] != L_('\0') + && p[1] != L_(']')); + + if (!is_range && c == fn) + goto matched; + +#if _LIBC + /* This is needed if we goto normal_bracket; from + outside of is_seqval's scope. */ + is_seqval = false; +#endif + + cold = c; + c = *p++; + } + + if (c == L_('-') && *p != L_(']')) + { +#if _LIBC + /* We have to find the collation sequence + value for C. Collation sequence is nothing + we can regularly access. The sequence + value is defined by the order in which the + definitions of the collation values for the + various characters appear in the source + file. A strange concept, nowhere + documented. */ + uint32_t fcollseq; + uint32_t lcollseq; + UCHAR cend = *p++; + +# ifdef WIDE_CHAR_VERSION + /* Search in the `names' array for the characters. */ + fcollseq = __collseq_table_lookup (collseq, fn); + if (fcollseq == ~((uint32_t) 0)) + /* XXX We don't know anything about the character + we are supposed to match. This means we are + failing. */ + goto range_not_matched; + + if (is_seqval) + lcollseq = cold; + else + lcollseq = __collseq_table_lookup (collseq, cold); +# else + fcollseq = collseq[fn]; + lcollseq = is_seqval ? cold : collseq[(UCHAR) cold]; +# endif + + is_seqval = false; + if (cend == L_('[') && *p == L_('.')) + { + uint32_t nrules = + _NL_CURRENT_WORD (LC_COLLATE, + _NL_COLLATE_NRULES); + const CHAR *startp = p; + size_t c1 = 0; + + while (1) + { + c = *++p; + if (c == L_('.') && p[1] == L_(']')) + { + p += 2; + break; + } + if (c == '\0') + return FNM_NOMATCH; + ++c1; + } + + if (nrules == 0) + { + /* There are no names defined in the + collation data. Therefore we only + accept the trivial names consisting + of the character itself. */ + if (c1 != 1) + return FNM_NOMATCH; + + cend = startp[1]; + } + else + { + int32_t table_size; + const int32_t *symb_table; +# ifdef WIDE_CHAR_VERSION + char str[c1]; + size_t strcnt; +# else +# define str (startp + 1) +# endif + const unsigned char *extra; + int32_t idx; + int32_t elem; + int32_t second; + int32_t hash; + +# ifdef WIDE_CHAR_VERSION + /* We have to convert the name to a single-byte + string. This is possible since the names + consist of ASCII characters and the internal + representation is UCS4. */ + for (strcnt = 0; strcnt < c1; ++strcnt) + str[strcnt] = startp[1 + strcnt]; +# endif + + table_size = + _NL_CURRENT_WORD (LC_COLLATE, + _NL_COLLATE_SYMB_HASH_SIZEMB); + symb_table = (const int32_t *) + _NL_CURRENT (LC_COLLATE, + _NL_COLLATE_SYMB_TABLEMB); + extra = (const unsigned char *) + _NL_CURRENT (LC_COLLATE, + _NL_COLLATE_SYMB_EXTRAMB); + + /* Locate the character in the hashing + table. */ + hash = elem_hash (str, c1); + + idx = 0; + elem = hash % table_size; + if (symb_table[2 * elem] != 0) + { + second = hash % (table_size - 2) + 1; + + do + { + /* First compare the hashing value. */ + if (symb_table[2 * elem] == hash + && (c1 + == extra[symb_table[2 * elem + 1]]) + && memcmp (str, + &extra[symb_table[2 * elem + 1] + + 1], c1) == 0) + { + /* Yep, this is the entry. */ + idx = symb_table[2 * elem + 1]; + idx += 1 + extra[idx]; + break; + } + + /* Next entry. */ + elem += second; + } + while (symb_table[2 * elem] != 0); + } + + if (symb_table[2 * elem] != 0) + { + /* Compare the byte sequence but only if + this is not part of a range. */ +# ifdef WIDE_CHAR_VERSION + int32_t *wextra; + + idx += 1 + extra[idx]; + /* Adjust for the alignment. */ + idx = (idx + 3) & ~4; + + wextra = (int32_t *) &extra[idx + 4]; +# endif + /* Get the collation sequence value. */ + is_seqval = true; +# ifdef WIDE_CHAR_VERSION + cend = wextra[1 + wextra[idx]]; +# else + /* Adjust for the alignment. */ + idx += 1 + extra[idx]; + idx = (idx + 3) & ~4; + cend = *((int32_t *) &extra[idx]); +# endif + } + else if (symb_table[2 * elem] != 0 && c1 == 1) + { + cend = str[0]; + c = *p++; + } + else + return FNM_NOMATCH; + } +# undef str + } + else + { + if (!(flags & FNM_NOESCAPE) && cend == L_('\\')) + cend = *p++; + if (cend == L_('\0')) + return FNM_NOMATCH; + cend = FOLD (cend); + } + + /* XXX It is not entirely clear to me how to handle + characters which are not mentioned in the + collation specification. */ + if ( +# ifdef WIDE_CHAR_VERSION + lcollseq == 0xffffffff || +# endif + lcollseq <= fcollseq) + { + /* We have to look at the upper bound. */ + uint32_t hcollseq; + + if (is_seqval) + hcollseq = cend; + else + { +# ifdef WIDE_CHAR_VERSION + hcollseq = + __collseq_table_lookup (collseq, cend); + if (hcollseq == ~((uint32_t) 0)) + { + /* Hum, no information about the upper + bound. The matching succeeds if the + lower bound is matched exactly. */ + if (lcollseq != fcollseq) + goto range_not_matched; + + goto matched; + } +# else + hcollseq = collseq[cend]; +# endif + } + + if (lcollseq <= hcollseq && fcollseq <= hcollseq) + goto matched; + } +# ifdef WIDE_CHAR_VERSION + range_not_matched: +# endif +#else + /* We use a boring value comparison of the character + values. This is better than comparing using + `strcoll' since the latter would have surprising + and sometimes fatal consequences. */ + UCHAR cend = *p++; + + if (!(flags & FNM_NOESCAPE) && cend == L_('\\')) + cend = *p++; + if (cend == L_('\0')) + return FNM_NOMATCH; + + /* It is a range. */ + if (cold <= fn && fn <= cend) + goto matched; +#endif + + c = *p++; + } + } + + if (c == L_(']')) + break; + } + + if (!not) + return FNM_NOMATCH; + break; + + matched: + /* Skip the rest of the [...] that already matched. */ + do + { + ignore_next: + c = *p++; + + if (c == L_('\0')) + /* [... (unterminated) loses. */ + return FNM_NOMATCH; + + if (!(flags & FNM_NOESCAPE) && c == L_('\\')) + { + if (*p == L_('\0')) + return FNM_NOMATCH; + /* XXX 1003.2d11 is unclear if this is right. */ + ++p; + } + else if (c == L_('[') && *p == L_(':')) + { + int c1 = 0; + const CHAR *startp = p; + + while (1) + { + c = *++p; + if (++c1 == CHAR_CLASS_MAX_LENGTH) + return FNM_NOMATCH; + + if (*p == L_(':') && p[1] == L_(']')) + break; + + if (c < L_('a') || c >= L_('z')) + { + p = startp; + goto ignore_next; + } + } + p += 2; + c = *p++; + } + else if (c == L_('[') && *p == L_('=')) + { + c = *++p; + if (c == L_('\0')) + return FNM_NOMATCH; + c = *++p; + if (c != L_('=') || p[1] != L_(']')) + return FNM_NOMATCH; + p += 2; + c = *p++; + } + else if (c == L_('[') && *p == L_('.')) + { + ++p; + while (1) + { + c = *++p; + if (c == '\0') + return FNM_NOMATCH; + + if (*p == L_('.') && p[1] == L_(']')) + break; + } + p += 2; + c = *p++; + } + } + while (c != L_(']')); + if (not) + return FNM_NOMATCH; + } + break; + + case L_('+'): + case L_('@'): + case L_('!'): + if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(') + { + int res; + + res = EXT (c, p, n, string_end, no_leading_period, flags); + if (res != -1) + return res; + } + goto normal_match; + + case L_('/'): + if (NO_LEADING_PERIOD (flags)) + { + if (n == string_end || c != (UCHAR) *n) + return FNM_NOMATCH; + + new_no_leading_period = true; + break; + } + /* FALLTHROUGH */ + default: + normal_match: + if (n == string_end || c != FOLD ((UCHAR) *n)) + return FNM_NOMATCH; + } + + no_leading_period = new_no_leading_period; + ++n; + } + + if (n == string_end) + return 0; + + if ((flags & FNM_LEADING_DIR) && n != string_end && *n == L_('/')) + /* The FNM_LEADING_DIR flag says that "foo*" matches "foobar/frobozz". */ + return 0; + + return FNM_NOMATCH; +} + + +static const CHAR * +internal_function +END (const CHAR *pattern) +{ + const CHAR *p = pattern; + + while (1) + if (*++p == L_('\0')) + /* This is an invalid pattern. */ + return pattern; + else if (*p == L_('[')) + { + /* Handle brackets special. */ + if (posixly_correct == 0) + posixly_correct = getenv ("POSIXLY_CORRECT") != NULL ? 1 : -1; + + /* Skip the not sign. We have to recognize it because of a possibly + following ']'. */ + if (*++p == L_('!') || (posixly_correct < 0 && *p == L_('^'))) + ++p; + /* A leading ']' is recognized as such. */ + if (*p == L_(']')) + ++p; + /* Skip over all characters of the list. */ + while (*p != L_(']')) + if (*p++ == L_('\0')) + /* This is no valid pattern. */ + return pattern; + } + else if ((*p == L_('?') || *p == L_('*') || *p == L_('+') || *p == L_('@') + || *p == L_('!')) && p[1] == L_('(')) + p = END (p + 1); + else if (*p == L_(')')) + break; + + return p + 1; +} + + +static int +internal_function +EXT (INT opt, const CHAR *pattern, const CHAR *string, const CHAR *string_end, + bool no_leading_period, int flags) +{ + const CHAR *startp; + size_t level; + struct patternlist + { + struct patternlist *next; + CHAR str[1]; + } *list = NULL; + struct patternlist **lastp = &list; + size_t pattern_len = STRLEN (pattern); + const CHAR *p; + const CHAR *rs; + enum { ALLOCA_LIMIT = 8000 }; + + /* Parse the pattern. Store the individual parts in the list. */ + level = 0; + for (startp = p = pattern + 1; ; ++p) + if (*p == L_('\0')) + /* This is an invalid pattern. */ + return -1; + else if (*p == L_('[')) + { + /* Handle brackets special. */ + if (posixly_correct == 0) + posixly_correct = getenv ("POSIXLY_CORRECT") != NULL ? 1 : -1; + + /* Skip the not sign. We have to recognize it because of a possibly + following ']'. */ + if (*++p == L_('!') || (posixly_correct < 0 && *p == L_('^'))) + ++p; + /* A leading ']' is recognized as such. */ + if (*p == L_(']')) + ++p; + /* Skip over all characters of the list. */ + while (*p != L_(']')) + if (*p++ == L_('\0')) + /* This is no valid pattern. */ + return -1; + } + else if ((*p == L_('?') || *p == L_('*') || *p == L_('+') || *p == L_('@') + || *p == L_('!')) && p[1] == L_('(')) + /* Remember the nesting level. */ + ++level; + else if (*p == L_(')')) + { + if (level-- == 0) + { + /* This means we found the end of the pattern. */ +#define NEW_PATTERN \ + struct patternlist *newp; \ + size_t plen; \ + size_t plensize; \ + size_t newpsize; \ + \ + plen = (opt == L_('?') || opt == L_('@') \ + ? pattern_len \ + : p - startp + 1); \ + plensize = plen * sizeof (CHAR); \ + newpsize = offsetof (struct patternlist, str) + plensize; \ + if ((size_t) -1 / sizeof (CHAR) < plen \ + || newpsize < offsetof (struct patternlist, str) \ + || ALLOCA_LIMIT <= newpsize) \ + return -1; \ + newp = (struct patternlist *) alloca (newpsize); \ + *((CHAR *) MEMPCPY (newp->str, startp, p - startp)) = L_('\0'); \ + newp->next = NULL; \ + *lastp = newp; \ + lastp = &newp->next + NEW_PATTERN; + break; + } + } + else if (*p == L_('|')) + { + if (level == 0) + { + NEW_PATTERN; + startp = p + 1; + } + } + assert (list != NULL); + assert (p[-1] == L_(')')); +#undef NEW_PATTERN + + switch (opt) + { + case L_('*'): + if (FCT (p, string, string_end, no_leading_period, flags) == 0) + return 0; + /* FALLTHROUGH */ + + case L_('+'): + do + { + for (rs = string; rs <= string_end; ++rs) + /* First match the prefix with the current pattern with the + current pattern. */ + if (FCT (list->str, string, rs, no_leading_period, + flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD) == 0 + /* This was successful. Now match the rest with the rest + of the pattern. */ + && (FCT (p, rs, string_end, + rs == string + ? no_leading_period + : rs[-1] == '/' && NO_LEADING_PERIOD (flags), + flags & FNM_FILE_NAME + ? flags : flags & ~FNM_PERIOD) == 0 + /* This didn't work. Try the whole pattern. */ + || (rs != string + && FCT (pattern - 1, rs, string_end, + rs == string + ? no_leading_period + : rs[-1] == '/' && NO_LEADING_PERIOD (flags), + flags & FNM_FILE_NAME + ? flags : flags & ~FNM_PERIOD) == 0))) + /* It worked. Signal success. */ + return 0; + } + while ((list = list->next) != NULL); + + /* None of the patterns lead to a match. */ + return FNM_NOMATCH; + + case L_('?'): + if (FCT (p, string, string_end, no_leading_period, flags) == 0) + return 0; + /* FALLTHROUGH */ + + case L_('@'): + do + /* I cannot believe it but `strcat' is actually acceptable + here. Match the entire string with the prefix from the + pattern list and the rest of the pattern following the + pattern list. */ + if (FCT (STRCAT (list->str, p), string, string_end, + no_leading_period, + flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD) == 0) + /* It worked. Signal success. */ + return 0; + while ((list = list->next) != NULL); + + /* None of the patterns lead to a match. */ + return FNM_NOMATCH; + + case L_('!'): + for (rs = string; rs <= string_end; ++rs) + { + struct patternlist *runp; + + for (runp = list; runp != NULL; runp = runp->next) + if (FCT (runp->str, string, rs, no_leading_period, + flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD) == 0) + break; + + /* If none of the patterns matched see whether the rest does. */ + if (runp == NULL + && (FCT (p, rs, string_end, + rs == string + ? no_leading_period + : rs[-1] == '/' && NO_LEADING_PERIOD (flags), + flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD) + == 0)) + /* This is successful. */ + return 0; + } + + /* None of the patterns together with the rest of the pattern + lead to a match. */ + return FNM_NOMATCH; + + default: + assert (! "Invalid extended matching operator"); + break; + } + + return -1; +} + + +#undef FOLD +#undef CHAR +#undef UCHAR +#undef INT +#undef FCT +#undef EXT +#undef END +#undef MEMPCPY +#undef MEMCHR +#undef STRCOLL +#undef STRLEN +#undef STRCAT +#undef L_ +#undef BTOWC diff --git a/src/bin/findutils/gnulib/lib/fopen-safer.c b/src/bin/findutils/gnulib/lib/fopen-safer.c new file mode 100644 index 0000000000..55991a2553 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fopen-safer.c @@ -0,0 +1,67 @@ +/* Invoke fopen, but avoid some glitches. + + Copyright (C) 2001, 2004, 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert. */ + +#include + +#include "stdio-safer.h" + +#include +#include +#include "unistd-safer.h" + +#ifndef STDERR_FILENO +# define STDERR_FILENO 2 +#endif + +/* Like fopen, but do not return stdin, stdout, or stderr. */ + +FILE * +fopen_safer (char const *file, char const *mode) +{ + FILE *fp = fopen (file, mode); + + if (fp) + { + int fd = fileno (fp); + + if (0 <= fd && fd <= STDERR_FILENO) + { + int f = dup_safer (fd); + + if (f < 0) + { + int e = errno; + fclose (fp); + errno = e; + return NULL; + } + + if (fclose (fp) != 0 + || ! (fp = fdopen (f, mode))) + { + int e = errno; + close (f); + errno = e; + return NULL; + } + } + } + + return fp; +} diff --git a/src/bin/findutils/gnulib/lib/fpending.c b/src/bin/findutils/gnulib/lib/fpending.c new file mode 100644 index 0000000000..9250d6af9d --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fpending.c @@ -0,0 +1,29 @@ +/* fpending.c -- return the number of pending output bytes on a stream + Copyright (C) 2000, 2004, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Jim Meyering. */ + +#include + +#include "fpending.h" + +/* Return the number of pending (aka buffered, unflushed) + bytes on the stream, FP, that is open for writing. */ +size_t +__fpending (FILE *fp) +{ + return PENDING_OUTPUT_N_BYTES; +} diff --git a/src/bin/findutils/gnulib/lib/fpending.h b/src/bin/findutils/gnulib/lib/fpending.h new file mode 100644 index 0000000000..c6a493ddf4 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fpending.h @@ -0,0 +1,33 @@ +/* Declare __fpending. + + Copyright (C) 2000, 2003, 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + Written by Jim Meyering. */ + +#include +#include + +#ifndef HAVE_DECL___FPENDING +"this configure-time declaration test was not run" +#endif + +#if HAVE_DECL___FPENDING +# if HAVE_STDIO_EXT_H +# include +# endif +#else +size_t __fpending (FILE *); +#endif diff --git a/src/bin/findutils/gnulib/lib/fpurge.c b/src/bin/findutils/gnulib/lib/fpurge.c new file mode 100644 index 0000000000..cc230fb1cd --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fpurge.c @@ -0,0 +1,121 @@ +/* Flushing buffers of a FILE stream. + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +/* Specification. */ +#include "fpurge.h" + +#if HAVE___FPURGE /* glibc >= 2.2, Solaris >= 7 */ +# include +#endif +#include + +int +fpurge (FILE *fp) +{ +#if HAVE___FPURGE /* glibc >= 2.2, Solaris >= 7 */ + + __fpurge (fp); + /* The __fpurge function does not have a return value. */ + return 0; + +#elif HAVE_FPURGE /* FreeBSD, NetBSD, OpenBSD, MacOS X */ + + /* Call the system's fpurge function. */ +# undef fpurge +# if !HAVE_DECL_FPURGE + extern int fpurge (FILE *); +# endif + int result = fpurge (fp); +# if defined __sferror /* FreeBSD, NetBSD, OpenBSD, MacOS X, Cygwin */ + if (result == 0) + /* Correct the invariants that fpurge broke. + on BSD systems says: + "The following always hold: if _flags & __SRD, _w is 0." + If this invariant is not fulfilled and the stream is read-write but + currently writing, subsequent putc or fputc calls will write directly + into the buffer, although they shouldn't be allowed to. */ + if ((fp->_flags & __SRD) != 0) + fp->_w = 0; +# endif + return result; + +#else + + /* Most systems provide FILE as a struct and the necessary bitmask in + , because they need it for implementing getc() and putc() as + fast macros. */ +# if defined _IO_ferror_unlocked /* GNU libc, BeOS */ + fp->_IO_read_end = fp->_IO_read_ptr; + fp->_IO_write_ptr = fp->_IO_write_base; + /* Avoid memory leak when there is an active ungetc buffer. */ + if (fp->_IO_save_base != NULL) + { + free (fp->_IO_save_base); + fp->_IO_save_base = NULL; + } + return 0; +# elif defined __sferror /* FreeBSD, NetBSD, OpenBSD, MacOS X, Cygwin */ + fp->_p = fp->_bf._base; + fp->_r = 0; + fp->_w = ((fp->_flags & (__SLBF | __SNBF | __SRD)) == 0 /* fully buffered and not currently reading? */ + ? fp->_bf._size + : 0); + /* Avoid memory leak when there is an active ungetc buffer. */ +# if defined __NetBSD__ || defined __OpenBSD__ /* NetBSD, OpenBSD */ + /* See + and */ +# define fp_ub ((struct { struct __sbuf _ub; } *) fp->_ext._base)->_ub +# else /* FreeBSD, MacOS X, Cygwin */ +# define fp_ub fp->_ub +# endif + if (fp_ub._base != NULL) + { + if (fp_ub._base != fp->_ubuf) + free (fp_ub._base); + fp_ub._base = NULL; + } + return 0; +# elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, mingw */ + fp->_ptr = fp->_base; + if (fp->_ptr != NULL) + fp->_cnt = 0; + return 0; +# elif defined __UCLIBC__ /* uClibc */ +# ifdef __STDIO_BUFFERS + if (fp->__modeflags & __FLAG_WRITING) + fp->__bufpos = fp->__bufstart; + else if (fp->__modeflags & (__FLAG_READONLY | __FLAG_READING)) + fp->__bufpos = fp->__bufread; +# endif + return 0; +# elif defined __QNX__ /* QNX */ + fp->_Rback = fp->_Back + sizeof (fp->_Back); + fp->_Rsave = NULL; + if (fp->_Mode & 0x2000 /* _MWRITE */) + /* fp->_Buf <= fp->_Next <= fp->_Wend */ + fp->_Next = fp->_Buf; + else + /* fp->_Buf <= fp->_Next <= fp->_Rend */ + fp->_Rend = fp->_Next; + return 0; +# else + #error "Please port gnulib fpurge.c to your platform! Look at the definitions of fflush, setvbuf and ungetc on your system, then report this to bug-gnulib." +# endif + +#endif +} diff --git a/src/bin/findutils/gnulib/lib/fpurge.h b/src/bin/findutils/gnulib/lib/fpurge.h new file mode 100644 index 0000000000..d7150a1a65 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fpurge.h @@ -0,0 +1,38 @@ +/* Flushing buffers of a FILE stream. + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef _GL_FPURGE_H +#define _GL_FPURGE_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Discard all pending buffered I/O on the stream STREAM. + STREAM must not be wide-character oriented. + Return 0 if successful. Upon error, return -1 and set errno. */ +#if HAVE_FPURGE +# define fpurge rpl_fpurge +#endif +extern int fpurge (FILE *stream); + +#ifdef __cplusplus +} +#endif + +#endif /* _GL_FPURGE_H */ diff --git a/src/bin/findutils/gnulib/lib/freadahead.c b/src/bin/findutils/gnulib/lib/freadahead.c new file mode 100644 index 0000000000..daad2901ad --- /dev/null +++ b/src/bin/findutils/gnulib/lib/freadahead.c @@ -0,0 +1,66 @@ +/* Retrieve information about a FILE stream. + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +/* Specification. */ +#include "freadahead.h" + +size_t +freadahead (FILE *fp) +{ +#if defined _IO_ferror_unlocked /* GNU libc, BeOS */ + if (fp->_IO_write_ptr > fp->_IO_write_base) + return 0; + return fp->_IO_read_end - fp->_IO_read_ptr; +#elif defined __sferror /* FreeBSD, NetBSD, OpenBSD, MacOS X, Cygwin */ + if ((fp->_flags & __SWR) != 0 || fp->_r < 0) + return 0; + return fp->_r; +#elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, mingw */ +# if defined __sun && defined _LP64 /* Solaris/{SPARC,AMD64} 64-bit */ +# define fp_ ((struct { unsigned char *_ptr; \ + unsigned char *_base; \ + unsigned char *_end; \ + long _cnt; \ + int _file; \ + unsigned int _flag; \ + } *) fp) + if ((fp_->_flag & _IOWRT) != 0) + return 0; + return fp_->_cnt; +# else + if ((fp->_flag & _IOWRT) != 0) + return 0; + return fp->_cnt; +# endif +#elif defined __UCLIBC__ /* uClibc */ +# ifdef __STDIO_BUFFERS + if (fp->__modeflags & __FLAG_WRITING) + return 0; + return fp->__bufread - fp->__bufpos; +# else + return 0; +# endif +#elif defined __QNX__ /* QNX */ + if ((fp->_Mode & 0x2000 /* _MWRITE */) != 0) + return 0; + /* fp->_Buf <= fp->_Next <= fp->_Rend */ + return fp->_Rend - fp->_Next; +#else + #error "Please port gnulib freadahead.c to your platform! Look at the definition of fflush, fread on your system, then report this to bug-gnulib." +#endif +} diff --git a/src/bin/findutils/gnulib/lib/freadahead.h b/src/bin/findutils/gnulib/lib/freadahead.h new file mode 100644 index 0000000000..430dcf870a --- /dev/null +++ b/src/bin/findutils/gnulib/lib/freadahead.h @@ -0,0 +1,36 @@ +/* Retrieve information about a FILE stream. + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Assuming the stream STREAM is open for reading: + Return the number of bytes waiting in the input buffer of STREAM. + + If this number is 0 and the stream is not currently writing, + fflush (STREAM) is known to be a no-op. + + STREAM must not be wide-character oriented. */ + +extern size_t freadahead (FILE *stream); + +#ifdef __cplusplus +} +#endif diff --git a/src/bin/findutils/gnulib/lib/freading.c b/src/bin/findutils/gnulib/lib/freading.c new file mode 100644 index 0000000000..dcdc3d24c8 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/freading.c @@ -0,0 +1,50 @@ +/* Retrieve information about a FILE stream. + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +/* Specification. */ +#include "freading.h" + +/* Don't use glibc's __freading function in glibc < 2.7, see + */ +#if !(HAVE___FREADING && (!defined __GLIBC__ || __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7))) + +bool +freading (FILE *fp) +{ + /* Most systems provide FILE as a struct and the necessary bitmask in + , because they need it for implementing getc() and putc() as + fast macros. */ +#if defined _IO_ferror_unlocked /* GNU libc, BeOS */ + return ((fp->_flags & _IO_NO_WRITES) != 0 + || ((fp->_flags & (_IO_NO_READS | _IO_CURRENTLY_PUTTING)) == 0 + && fp->_IO_read_base != NULL)); +#elif defined __sferror /* FreeBSD, NetBSD, OpenBSD, MacOS X, Cygwin */ + return (fp->_flags & __SRD) != 0; +#elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, mingw */ + return (fp->_flag & _IOREAD) != 0; +#elif defined __UCLIBC__ /* uClibc */ + return (fp->__modeflags & (__FLAG_READONLY | __FLAG_READING)) != 0; +#elif defined __QNX__ /* QNX */ + return ((fp->_Mode & 0x2 /* _MOPENW */) == 0 + || (fp->_Mode & 0x1000 /* _MREAD */) != 0); +#else + #error "Please port gnulib freading.c to your platform!" +#endif +} + +#endif diff --git a/src/bin/findutils/gnulib/lib/freading.h b/src/bin/findutils/gnulib/lib/freading.h new file mode 100644 index 0000000000..bf67b0750d --- /dev/null +++ b/src/bin/findutils/gnulib/lib/freading.h @@ -0,0 +1,53 @@ +/* Retrieve information about a FILE stream. + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include +#include + +/* Return true if the stream STREAM is opened read-only, or if the + last operation on the stream was a read operation. Return false if + the stream is opened write-only or append-only, or if it supports + writing and there is no current read operation (such as fputc). + + freading and fwriting will never both be true. If STREAM supports + both reads and writes, then: + - both freading and fwriting might be false when the stream is first + opened, after read encounters EOF, or after fflush, + - freading might be false or true and fwriting might be false + after repositioning (such as fseek, fsetpos, or rewind), + depending on the underlying implementation. + + STREAM must not be wide-character oriented. */ + +#if HAVE___FREADING && (!defined __GLIBC__ || __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7)) +/* Solaris >= 7, not glibc >= 2.2, but glibc >= 2.7 */ + +# include +# define freading(stream) (__freading (stream) != 0) + +#else + +# ifdef __cplusplus +extern "C" { +# endif + +extern bool freading (FILE *stream); + +# ifdef __cplusplus +} +# endif + +#endif diff --git a/src/bin/findutils/gnulib/lib/fseeko.c b/src/bin/findutils/gnulib/lib/fseeko.c new file mode 100644 index 0000000000..8fffb2b0f6 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fseeko.c @@ -0,0 +1,120 @@ +/* An fseeko() function that, together with fflush(), is POSIX compliant. + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#include + +/* Specification. */ +#include + +/* Get off_t and lseek. */ +#include + +#undef fseeko +#if !HAVE_FSEEKO +# undef fseek +# define fseeko fseek +#endif + +int +rpl_fseeko (FILE *fp, off_t offset, int whence) +{ +#if LSEEK_PIPE_BROKEN + /* mingw gives bogus answers rather than failure on non-seekable files. */ + if (lseek (fileno (fp), 0, SEEK_CUR) == -1) + return EOF; +#endif + + /* These tests are based on fpurge.c. */ +#if defined _IO_ferror_unlocked /* GNU libc, BeOS */ + if (fp->_IO_read_end == fp->_IO_read_ptr + && fp->_IO_write_ptr == fp->_IO_write_base + && fp->_IO_save_base == NULL) +#elif defined __sferror /* FreeBSD, NetBSD, OpenBSD, MacOS X, Cygwin */ +# if defined __NetBSD__ || defined __OpenBSD__ /* NetBSD, OpenBSD */ + /* See + and */ +# define fp_ub ((struct { struct __sbuf _ub; } *) fp->_ext._base)->_ub +# else /* FreeBSD, MacOS X, Cygwin */ +# define fp_ub fp->_ub +# endif +# if defined __SL64 && defined __SCLE /* Cygwin */ + if ((fp->_flags & __SL64) == 0) + { + /* Cygwin 1.5.0 through 1.5.24 failed to open stdin in 64-bit + mode; but has an fseeko that requires 64-bit mode. */ + FILE *tmp = fopen ("/dev/null", "r"); + if (!tmp) + return -1; + fp->_flags |= __SL64; + fp->_seek64 = tmp->_seek64; + fclose (tmp); + } +# endif + if (fp->_p == fp->_bf._base + && fp->_r == 0 + && fp->_w == ((fp->_flags & (__SLBF | __SNBF | __SRD)) == 0 /* fully buffered and not currently reading? */ + ? fp->_bf._size + : 0) + && fp_ub._base == NULL) +#elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, mingw */ +# if defined __sun && defined _LP64 /* Solaris/{SPARC,AMD64} 64-bit */ +# define fp_ ((struct { unsigned char *_ptr; \ + unsigned char *_base; \ + unsigned char *_end; \ + long _cnt; \ + int _file; \ + unsigned int _flag; \ + } *) fp) + if (fp_->_ptr == fp_->_base + && (fp_->_ptr == NULL || fp_->_cnt == 0)) +# else + if (fp->_ptr == fp->_base + && (fp->_ptr == NULL || fp->_cnt == 0)) +# endif +#elif defined __UCLIBC__ /* uClibc */ + if (((fp->__modeflags & __FLAG_WRITING) == 0 + || fp->__bufpos == fp->__bufstart) + && ((fp->__modeflags & (__FLAG_READONLY | __FLAG_READING)) == 0 + || fp->__bufpos == fp->__bufread)) +#elif defined __QNX__ /* QNX */ + if ((fp->_Mode & _MWRITE ? fp->_Next == fp->_Buf : fp->_Next == fp->_Rend) + && fp->_Rback == fp->_Back + sizeof (fp->_Back) + && fp->_Rsave == NULL) +#else + #error "Please port gnulib fseeko.c to your platform! Look at the code in fpurge.c, then report this to bug-gnulib." +#endif + { + off_t pos = lseek (fileno (fp), offset, whence); + if (pos == -1) + { +#if defined __sferror /* FreeBSD, NetBSD, OpenBSD, MacOS X, Cygwin */ + fp->_flags &= ~__SOFF; +#endif + return -1; + } + else + { +#if defined __sferror /* FreeBSD, NetBSD, OpenBSD, MacOS X, Cygwin */ + fp->_offset = pos; + fp->_flags |= __SOFF; +#endif + return 0; + } + } + else + return fseeko (fp, offset, whence); +} diff --git a/src/bin/findutils/gnulib/lib/fstatat.c b/src/bin/findutils/gnulib/lib/fstatat.c new file mode 100644 index 0000000000..8b6291225f --- /dev/null +++ b/src/bin/findutils/gnulib/lib/fstatat.c @@ -0,0 +1,56 @@ +/* Work around an fstatat bug on Solaris 9. + + Copyright (C) 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert and Jim Meyering. */ + +#include + +#define COMPILING_FSTATAT 1 +#include "openat.h" + +#include +#include + +/* fstatat should always follow symbolic links that end in /, but on + Solaris 9 it doesn't if AT_SYMLINK_NOFOLLOW is specified. This is + the same problem that lstat.c addresses, so solve it in a similar + way. */ + +int +rpl_fstatat (int fd, char const *file, struct stat *st, int flag) +{ + int result = fstatat (fd, file, st, flag); + + if (result == 0 && (flag & AT_SYMLINK_NOFOLLOW) && S_ISLNK (st->st_mode) + && file[strlen (file) - 1] == '/') + { + /* FILE refers to a symbolic link and the name ends with a slash. + Get info about the link's referent. */ + result = fstatat (fd, file, st, flag & ~AT_SYMLINK_NOFOLLOW); + if (result == 0 && ! S_ISDIR (st->st_mode)) + { + /* fstatat succeeded and FILE references a non-directory. + But it was specified via a name including a trailing + slash. Fail with errno set to ENOTDIR to indicate the + contradiction. */ + errno = ENOTDIR; + return -1; + } + } + + return result; +} diff --git a/src/bin/findutils/gnulib/lib/ftello.c b/src/bin/findutils/gnulib/lib/ftello.c new file mode 100644 index 0000000000..f2524084c3 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/ftello.c @@ -0,0 +1,54 @@ +/* An ftello() function that works around platform bugs. + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +/* Specification. */ +#include + +/* Get lseek. */ +#include + +#undef ftello +#if !HAVE_FTELLO +# undef ftell +# define ftello ftell +#endif + +off_t +rpl_ftello (FILE *fp) +{ +#if LSEEK_PIPE_BROKEN + /* mingw gives bogus answers rather than failure on non-seekable files. */ + if (lseek (fileno (fp), 0, SEEK_CUR) == -1) + return -1; +#endif + +#if defined __SL64 && defined __SCLE /* Cygwin */ + if ((fp->_flags & __SL64) == 0) + { + /* Cygwin 1.5.0 through 1.5.24 failed to open stdin in 64-bit + mode; but has an ftello that requires 64-bit mode. */ + FILE *tmp = fopen ("/dev/null", "r"); + if (!tmp) + return -1; + fp->_flags |= __SL64; + fp->_seek64 = tmp->_seek64; + fclose (tmp); + } +#endif + return ftello (fp); +} diff --git a/src/bin/findutils/gnulib/lib/getcwd.c b/src/bin/findutils/gnulib/lib/getcwd.c new file mode 100644 index 0000000000..b8e9989b90 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/getcwd.c @@ -0,0 +1,427 @@ +/* Copyright (C) 1991,92,93,94,95,96,97,98,99,2004,2005,2006,2007 Free Software + Foundation, Inc. + This file is part of the GNU C Library. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#if !_LIBC +# include +# include +# include "dirfd.h" +#endif + +#include +#include +#include +#include +#include + +#include /* For AT_FDCWD on Solaris 9. */ + +#ifndef __set_errno +# define __set_errno(val) (errno = (val)) +#endif + +#include +#ifndef _D_EXACT_NAMLEN +# define _D_EXACT_NAMLEN(d) strlen ((d)->d_name) +#endif +#ifndef _D_ALLOC_NAMLEN +# define _D_ALLOC_NAMLEN(d) (_D_EXACT_NAMLEN (d) + 1) +#endif + +#include +#include +#include + +#if _LIBC +# ifndef mempcpy +# define mempcpy __mempcpy +# endif +#endif + +#include + +/* Work around a bug in Solaris 9 and 10: AT_FDCWD is positive. Its + value exceeds INT_MAX, so its use as an int doesn't conform to the + C standard, and GCC and Sun C complain in some cases. */ +#if 0 < AT_FDCWD && AT_FDCWD == 0xffd19553 +# undef AT_FDCWD +# define AT_FDCWD (-3041965) +#endif + +#ifdef ENAMETOOLONG +# define is_ENAMETOOLONG(x) ((x) == ENAMETOOLONG) +#else +# define is_ENAMETOOLONG(x) 0 +#endif + +#ifndef MAX +# define MAX(a, b) ((a) < (b) ? (b) : (a)) +#endif +#ifndef MIN +# define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +#ifndef PATH_MAX +# ifdef MAXPATHLEN +# define PATH_MAX MAXPATHLEN +# else +# define PATH_MAX 1024 +# endif +#endif + +#if D_INO_IN_DIRENT +# define MATCHING_INO(dp, ino) ((dp)->d_ino == (ino)) +#else +# define MATCHING_INO(dp, ino) true +#endif + +#if !_LIBC +# define __getcwd rpl_getcwd +# define __lstat lstat +# define __closedir closedir +# define __opendir opendir +# define __readdir readdir +#endif + +/* The results of opendir() in this file are not used with dirfd and fchdir, + therefore save some unnecessary recursion in fchdir.c. */ +#undef opendir +#undef closedir + +/* Get the name of the current working directory, and put it in SIZE + bytes of BUF. Returns NULL if the directory couldn't be determined or + SIZE was too small. If successful, returns BUF. In GNU, if BUF is + NULL, an array is allocated with `malloc'; the array is SIZE bytes long, + unless SIZE == 0, in which case it is as big as necessary. */ + +char * +__getcwd (char *buf, size_t size) +{ + /* Lengths of big file name components and entire file names, and a + deep level of file name nesting. These numbers are not upper + bounds; they are merely large values suitable for initial + allocations, designed to be large enough for most real-world + uses. */ + enum + { + BIG_FILE_NAME_COMPONENT_LENGTH = 255, + BIG_FILE_NAME_LENGTH = MIN (4095, PATH_MAX - 1), + DEEP_NESTING = 100 + }; + +#ifdef AT_FDCWD + int fd = AT_FDCWD; + bool fd_needs_closing = false; +#else + char dots[DEEP_NESTING * sizeof ".." + BIG_FILE_NAME_COMPONENT_LENGTH + 1]; + char *dotlist = dots; + size_t dotsize = sizeof dots; + size_t dotlen = 0; +#endif + DIR *dirstream = NULL; + dev_t rootdev, thisdev; + ino_t rootino, thisino; + char *dir; + register char *dirp; + struct stat st; + size_t allocated = size; + size_t used; + +#if HAVE_PARTLY_WORKING_GETCWD + /* The system getcwd works, except it sometimes fails when it + shouldn't, setting errno to ERANGE, ENAMETOOLONG, or ENOENT. If + AT_FDCWD is not defined, the algorithm below is O(N**2) and this + is much slower than the system getcwd (at least on GNU/Linux). + So trust the system getcwd's results unless they look + suspicious. + + Use the system getcwd even if we have openat support, since the + system getcwd works even when a parent is unreadable, while the + openat-based approach does not. */ + +# undef getcwd + dir = getcwd (buf, size); + if (dir || (errno != ERANGE && !is_ENAMETOOLONG (errno) && errno != ENOENT)) + return dir; +#endif + + if (size == 0) + { + if (buf != NULL) + { + __set_errno (EINVAL); + return NULL; + } + + allocated = BIG_FILE_NAME_LENGTH + 1; + } + + if (buf == NULL) + { + dir = malloc (allocated); + if (dir == NULL) + return NULL; + } + else + dir = buf; + + dirp = dir + allocated; + *--dirp = '\0'; + + if (__lstat (".", &st) < 0) + goto lose; + thisdev = st.st_dev; + thisino = st.st_ino; + + if (__lstat ("/", &st) < 0) + goto lose; + rootdev = st.st_dev; + rootino = st.st_ino; + + while (!(thisdev == rootdev && thisino == rootino)) + { + struct dirent *d; + dev_t dotdev; + ino_t dotino; + bool mount_point; + int parent_status; + size_t dirroom; + size_t namlen; + bool use_d_ino = true; + + /* Look at the parent directory. */ +#ifdef AT_FDCWD + fd = openat (fd, "..", O_RDONLY); + if (fd < 0) + goto lose; + fd_needs_closing = true; + parent_status = fstat (fd, &st); +#else + dotlist[dotlen++] = '.'; + dotlist[dotlen++] = '.'; + dotlist[dotlen] = '\0'; + parent_status = __lstat (dotlist, &st); +#endif + if (parent_status != 0) + goto lose; + + if (dirstream && __closedir (dirstream) != 0) + { + dirstream = NULL; + goto lose; + } + + /* Figure out if this directory is a mount point. */ + dotdev = st.st_dev; + dotino = st.st_ino; + mount_point = dotdev != thisdev; + + /* Search for the last directory. */ +#ifdef AT_FDCWD + dirstream = fdopendir (fd); + if (dirstream == NULL) + goto lose; + /* Reset fd. It may have been closed by fdopendir. */ + fd = dirfd (dirstream); + fd_needs_closing = false; +#else + dirstream = __opendir (dotlist); + if (dirstream == NULL) + goto lose; + dotlist[dotlen++] = '/'; +#endif + for (;;) + { + /* Clear errno to distinguish EOF from error if readdir returns + NULL. */ + __set_errno (0); + d = __readdir (dirstream); + + /* When we've iterated through all directory entries without finding + one with a matching d_ino, rewind the stream and consider each + name again, but this time, using lstat. This is necessary in a + chroot on at least one system (glibc-2.3.6 + linux 2.6.12), where + .., ../.., ../../.., etc. all had the same device number, yet the + d_ino values for entries in / did not match those obtained + via lstat. */ + if (d == NULL && errno == 0 && use_d_ino) + { + use_d_ino = false; + rewinddir (dirstream); + d = __readdir (dirstream); + } + + if (d == NULL) + { + if (errno == 0) + /* EOF on dirstream, which can mean e.g., that the current + directory has been removed. */ + __set_errno (ENOENT); + goto lose; + } + if (d->d_name[0] == '.' && + (d->d_name[1] == '\0' || + (d->d_name[1] == '.' && d->d_name[2] == '\0'))) + continue; + + if (use_d_ino) + { + bool match = (MATCHING_INO (d, thisino) || mount_point); + if (! match) + continue; + } + + { + int entry_status; +#ifdef AT_FDCWD + entry_status = fstatat (fd, d->d_name, &st, AT_SYMLINK_NOFOLLOW); +#else + /* Compute size needed for this file name, or for the file + name ".." in the same directory, whichever is larger. + Room for ".." might be needed the next time through + the outer loop. */ + size_t name_alloc = _D_ALLOC_NAMLEN (d); + size_t filesize = dotlen + MAX (sizeof "..", name_alloc); + + if (filesize < dotlen) + goto memory_exhausted; + + if (dotsize < filesize) + { + /* My, what a deep directory tree you have, Grandma. */ + size_t newsize = MAX (filesize, dotsize * 2); + size_t i; + if (newsize < dotsize) + goto memory_exhausted; + if (dotlist != dots) + free (dotlist); + dotlist = malloc (newsize); + if (dotlist == NULL) + goto lose; + dotsize = newsize; + + i = 0; + do + { + dotlist[i++] = '.'; + dotlist[i++] = '.'; + dotlist[i++] = '/'; + } + while (i < dotlen); + } + + memcpy (dotlist + dotlen, d->d_name, _D_ALLOC_NAMLEN (d)); + entry_status = __lstat (dotlist, &st); +#endif + /* We don't fail here if we cannot stat() a directory entry. + This can happen when (network) file systems fail. If this + entry is in fact the one we are looking for we will find + out soon as we reach the end of the directory without + having found anything. */ + if (entry_status == 0 && S_ISDIR (st.st_mode) + && st.st_dev == thisdev && st.st_ino == thisino) + break; + } + } + + dirroom = dirp - dir; + namlen = _D_EXACT_NAMLEN (d); + + if (dirroom <= namlen) + { + if (size != 0) + { + __set_errno (ERANGE); + goto lose; + } + else + { + char *tmp; + size_t oldsize = allocated; + + allocated += MAX (allocated, namlen); + if (allocated < oldsize + || ! (tmp = realloc (dir, allocated))) + goto memory_exhausted; + + /* Move current contents up to the end of the buffer. + This is guaranteed to be non-overlapping. */ + dirp = memcpy (tmp + allocated - (oldsize - dirroom), + tmp + dirroom, + oldsize - dirroom); + dir = tmp; + } + } + dirp -= namlen; + memcpy (dirp, d->d_name, namlen); + *--dirp = '/'; + + thisdev = dotdev; + thisino = dotino; + } + + if (dirstream && __closedir (dirstream) != 0) + { + dirstream = NULL; + goto lose; + } + + if (dirp == &dir[allocated - 1]) + *--dirp = '/'; + +#ifndef AT_FDCWD + if (dotlist != dots) + free (dotlist); +#endif + + used = dir + allocated - dirp; + memmove (dir, dirp, used); + + if (size == 0) + /* Ensure that the buffer is only as large as necessary. */ + buf = realloc (dir, used); + + if (buf == NULL) + /* Either buf was NULL all along, or `realloc' failed but + we still have the original string. */ + buf = dir; + + return buf; + + memory_exhausted: + __set_errno (ENOMEM); + lose: + { + int save = errno; + if (dirstream) + __closedir (dirstream); +#ifdef AT_FDCWD + if (fd_needs_closing) + close (fd); +#else + if (dotlist != dots) + free (dotlist); +#endif + if (buf == NULL) + free (dir); + __set_errno (save); + } + return NULL; +} + +#ifdef weak_alias +weak_alias (__getcwd, getcwd) +#endif diff --git a/src/bin/findutils/gnulib/lib/getdelim.c b/src/bin/findutils/gnulib/lib/getdelim.c new file mode 100644 index 0000000000..99b2ffd23a --- /dev/null +++ b/src/bin/findutils/gnulib/lib/getdelim.c @@ -0,0 +1,133 @@ +/* getdelim.c --- Implementation of replacement getdelim function. + Copyright (C) 1994, 1996, 1997, 1998, 2001, 2003, 2005, 2006, 2007 Free + Software Foundation, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 3, or (at + your option) any later version. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301, USA. */ + +/* Ported from glibc by Simon Josefsson. */ + +#include + +#include + +#include +#include +#include + +#ifndef SIZE_MAX +# define SIZE_MAX ((size_t) -1) +#endif +#ifndef SSIZE_MAX +# define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2)) +#endif +#if !HAVE_FLOCKFILE +# undef flockfile +# define flockfile(x) ((void) 0) +#endif +#if !HAVE_FUNLOCKFILE +# undef funlockfile +# define funlockfile(x) ((void) 0) +#endif + +/* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */ +#ifndef EOVERFLOW +# define EOVERFLOW E2BIG +#endif + +/* Read up to (and including) a DELIMITER from FP into *LINEPTR (and + NUL-terminate it). *LINEPTR is a pointer returned from malloc (or + NULL), pointing to *N characters of space. It is realloc'ed as + necessary. Returns the number of characters read (not including + the null terminator), or -1 on error or EOF. */ + +ssize_t +getdelim (char **lineptr, size_t *n, int delimiter, FILE *fp) +{ + ssize_t result; + size_t cur_len = 0; + + if (lineptr == NULL || n == NULL || fp == NULL) + { + errno = EINVAL; + return -1; + } + + flockfile (fp); + + if (*lineptr == NULL || *n == 0) + { + *n = 120; + *lineptr = (char *) realloc (*lineptr, *n); + if (*lineptr == NULL) + { + result = -1; + goto unlock_return; + } + } + + for (;;) + { + int i; + + i = getc (fp); + if (i == EOF) + { + result = -1; + break; + } + + /* Make enough space for len+1 (for final NUL) bytes. */ + if (cur_len + 1 >= *n) + { + size_t needed_max = + SSIZE_MAX < SIZE_MAX ? (size_t) SSIZE_MAX + 1 : SIZE_MAX; + size_t needed = 2 * *n + 1; /* Be generous. */ + char *new_lineptr; + + if (needed_max < needed) + needed = needed_max; + if (cur_len + 1 >= needed) + { + result = -1; + errno = EOVERFLOW; + goto unlock_return; + } + + new_lineptr = (char *) realloc (*lineptr, needed); + if (new_lineptr == NULL) + { + result = -1; + goto unlock_return; + } + + *lineptr = new_lineptr; + *n = needed; + } + + (*lineptr)[cur_len] = i; + cur_len++; + + if (i == delimiter) + break; + } + (*lineptr)[cur_len] = '\0'; + result = cur_len ? cur_len : result; + + unlock_return: + funlockfile (fp); /* doesn't set errno */ + + return result; +} diff --git a/src/bin/findutils/gnulib/lib/getline.c b/src/bin/findutils/gnulib/lib/getline.c new file mode 100644 index 0000000000..a653648f05 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/getline.c @@ -0,0 +1,29 @@ +/* getline.c --- Implementation of replacement getline function. + Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 3, or (at + your option) any later version. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301, USA. */ + +/* Written by Simon Josefsson. */ + +#include + +#include + +ssize_t +getline (char **lineptr, size_t *n, FILE *stream) +{ + return getdelim (lineptr, n, '\n', stream); +} diff --git a/src/bin/findutils/gnulib/lib/getopt.c b/src/bin/findutils/gnulib/lib/getopt.c new file mode 100644 index 0000000000..3c23601997 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/getopt.c @@ -0,0 +1,1190 @@ +/* Getopt for GNU. + NOTE: getopt is now part of the C library, so if you don't know what + "Keep this file name-space clean" means, talk to drepper@gnu.org + before changing it! + Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001,2002,2003,2004,2006 + Free Software Foundation, Inc. + This file is part of the GNU C Library. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef _LIBC +# include +#endif + +#include "getopt.h" + +#include +#include +#include +#include + +#ifdef __VMS +# include +#endif + +#ifdef _LIBC +# include +#else +# include "gettext.h" +# define _(msgid) gettext (msgid) +#endif + +#if defined _LIBC && defined USE_IN_LIBIO +# include +#endif + +#ifndef attribute_hidden +# define attribute_hidden +#endif + +/* Unlike standard Unix `getopt', functions like `getopt_long' + let the user intersperse the options with the other arguments. + + As `getopt_long' works, it permutes the elements of ARGV so that, + when it is done, all the options precede everything else. Thus + all application programs are extended to handle flexible argument order. + + Using `getopt' or setting the environment variable POSIXLY_CORRECT + disables permutation. + Then the application's behavior is completely standard. + + GNU application programs can use a third alternative mode in which + they can distinguish the relative order of options and other arguments. */ + +#include "getopt_int.h" + +/* For communication from `getopt' to the caller. + When `getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + +char *optarg; + +/* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `getopt'. + + On entry to `getopt', zero means this is the first call; initialize. + + When `getopt' returns -1, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + +/* 1003.2 says this must be 1 before any call. */ +int optind = 1; + +/* Callers store zero here to inhibit the error message + for unrecognized options. */ + +int opterr = 1; + +/* Set to an option character which was unrecognized. + This must be initialized on some systems to avoid linking in the + system's own getopt implementation. */ + +int optopt = '?'; + +/* Keep a global copy of all internal members of getopt_data. */ + +static struct _getopt_data getopt_data; + + +#if defined HAVE_DECL_GETENV && !HAVE_DECL_GETENV +extern char *getenv (); +#endif + +#ifdef _LIBC +/* Stored original parameters. + XXX This is no good solution. We should rather copy the args so + that we can compare them later. But we must not use malloc(3). */ +extern int __libc_argc; +extern char **__libc_argv; + +/* Bash 2.0 gives us an environment variable containing flags + indicating ARGV elements that should not be considered arguments. */ + +# ifdef USE_NONOPTION_FLAGS +/* Defined in getopt_init.c */ +extern char *__getopt_nonoption_flags; +# endif + +# ifdef USE_NONOPTION_FLAGS +# define SWAP_FLAGS(ch1, ch2) \ + if (d->__nonoption_flags_len > 0) \ + { \ + char __tmp = __getopt_nonoption_flags[ch1]; \ + __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ + __getopt_nonoption_flags[ch2] = __tmp; \ + } +# else +# define SWAP_FLAGS(ch1, ch2) +# endif +#else /* !_LIBC */ +# define SWAP_FLAGS(ch1, ch2) +#endif /* _LIBC */ + +/* Exchange two adjacent subsequences of ARGV. + One subsequence is elements [first_nonopt,last_nonopt) + which contains all the non-options that have been skipped so far. + The other is elements [last_nonopt,optind), which contains all + the options processed since those non-options were skipped. + + `first_nonopt' and `last_nonopt' are relocated so that they describe + the new indices of the non-options in ARGV after they are moved. */ + +static void +exchange (char **argv, struct _getopt_data *d) +{ + int bottom = d->__first_nonopt; + int middle = d->__last_nonopt; + int top = d->optind; + char *tem; + + /* Exchange the shorter segment with the far end of the longer segment. + That puts the shorter segment into the right place. + It leaves the longer segment in the right place overall, + but it consists of two parts that need to be swapped next. */ + +#if defined _LIBC && defined USE_NONOPTION_FLAGS + /* First make sure the handling of the `__getopt_nonoption_flags' + string can work normally. Our top argument must be in the range + of the string. */ + if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len) + { + /* We must extend the array. The user plays games with us and + presents new arguments. */ + char *new_str = malloc (top + 1); + if (new_str == NULL) + d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0; + else + { + memset (__mempcpy (new_str, __getopt_nonoption_flags, + d->__nonoption_flags_max_len), + '\0', top + 1 - d->__nonoption_flags_max_len); + d->__nonoption_flags_max_len = top + 1; + __getopt_nonoption_flags = new_str; + } + } +#endif + + while (top > middle && middle > bottom) + { + if (top - middle > middle - bottom) + { + /* Bottom segment is the short one. */ + int len = middle - bottom; + register int i; + + /* Swap it with the top part of the top segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[top - (middle - bottom) + i]; + argv[top - (middle - bottom) + i] = tem; + SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); + } + /* Exclude the moved bottom segment from further swapping. */ + top -= len; + } + else + { + /* Top segment is the short one. */ + int len = top - middle; + register int i; + + /* Swap it with the bottom part of the bottom segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[middle + i]; + argv[middle + i] = tem; + SWAP_FLAGS (bottom + i, middle + i); + } + /* Exclude the moved top segment from further swapping. */ + bottom += len; + } + } + + /* Update records for the slots the non-options now occupy. */ + + d->__first_nonopt += (d->optind - d->__last_nonopt); + d->__last_nonopt = d->optind; +} + +/* Initialize the internal data when the first call is made. */ + +static const char * +_getopt_initialize (int argc, char **argv, const char *optstring, + int posixly_correct, struct _getopt_data *d) +{ + /* Start processing options with ARGV-element 1 (since ARGV-element 0 + is the program name); the sequence of previously skipped + non-option ARGV-elements is empty. */ + + d->__first_nonopt = d->__last_nonopt = d->optind; + + d->__nextchar = NULL; + + d->__posixly_correct = posixly_correct || !!getenv ("POSIXLY_CORRECT"); + + /* Determine how to handle the ordering of options and nonoptions. */ + + if (optstring[0] == '-') + { + d->__ordering = RETURN_IN_ORDER; + ++optstring; + } + else if (optstring[0] == '+') + { + d->__ordering = REQUIRE_ORDER; + ++optstring; + } + else if (d->__posixly_correct) + d->__ordering = REQUIRE_ORDER; + else + d->__ordering = PERMUTE; + +#if defined _LIBC && defined USE_NONOPTION_FLAGS + if (!d->__posixly_correct + && argc == __libc_argc && argv == __libc_argv) + { + if (d->__nonoption_flags_max_len == 0) + { + if (__getopt_nonoption_flags == NULL + || __getopt_nonoption_flags[0] == '\0') + d->__nonoption_flags_max_len = -1; + else + { + const char *orig_str = __getopt_nonoption_flags; + int len = d->__nonoption_flags_max_len = strlen (orig_str); + if (d->__nonoption_flags_max_len < argc) + d->__nonoption_flags_max_len = argc; + __getopt_nonoption_flags = + (char *) malloc (d->__nonoption_flags_max_len); + if (__getopt_nonoption_flags == NULL) + d->__nonoption_flags_max_len = -1; + else + memset (__mempcpy (__getopt_nonoption_flags, orig_str, len), + '\0', d->__nonoption_flags_max_len - len); + } + } + d->__nonoption_flags_len = d->__nonoption_flags_max_len; + } + else + d->__nonoption_flags_len = 0; +#endif + + return optstring; +} + +/* Scan elements of ARGV (whose length is ARGC) for option characters + given in OPTSTRING. + + If an element of ARGV starts with '-', and is not exactly "-" or "--", + then it is an option element. The characters of this element + (aside from the initial '-') are option characters. If `getopt' + is called repeatedly, it returns successively each of the option characters + from each of the option elements. + + If `getopt' finds another option character, it returns that character, + updating `optind' and `nextchar' so that the next call to `getopt' can + resume the scan with the following option character or ARGV-element. + + If there are no more option characters, `getopt' returns -1. + Then `optind' is the index in ARGV of the first ARGV-element + that is not an option. (The ARGV-elements have been permuted + so that those that are not options now come last.) + + OPTSTRING is a string containing the legitimate option characters. + If an option character is seen that is not listed in OPTSTRING, + return '?' after printing an error message. If you set `opterr' to + zero, the error message is suppressed but we still return '?'. + + If a char in OPTSTRING is followed by a colon, that means it wants an arg, + so the following text in the same ARGV-element, or the text of the following + ARGV-element, is returned in `optarg'. Two colons mean an option that + wants an optional arg; if there is text in the current ARGV-element, + it is returned in `optarg', otherwise `optarg' is set to zero. + + If OPTSTRING starts with `-' or `+', it requests different methods of + handling the non-option ARGV-elements. + See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. + + Long-named options begin with `--' instead of `-'. + Their names may be abbreviated as long as the abbreviation is unique + or is an exact match for some defined option. If they have an + argument, it follows the option name in the same ARGV-element, separated + from the option name by a `=', or else the in next ARGV-element. + When `getopt' finds a long-named option, it returns 0 if that option's + `flag' field is nonzero, the value of the option's `val' field + if the `flag' field is zero. + + LONGOPTS is a vector of `struct option' terminated by an + element containing a name which is zero. + + LONGIND returns the index in LONGOPT of the long-named option found. + It is only valid when a long-named option has been found by the most + recent call. + + If LONG_ONLY is nonzero, '-' as well as '--' can introduce + long-named options. + + If POSIXLY_CORRECT is nonzero, behave as if the POSIXLY_CORRECT + environment variable were set. */ + +int +_getopt_internal_r (int argc, char **argv, const char *optstring, + const struct option *longopts, int *longind, + int long_only, int posixly_correct, struct _getopt_data *d) +{ + int print_errors = d->opterr; + if (optstring[0] == ':') + print_errors = 0; + + if (argc < 1) + return -1; + + d->optarg = NULL; + + if (d->optind == 0 || !d->__initialized) + { + if (d->optind == 0) + d->optind = 1; /* Don't scan ARGV[0], the program name. */ + optstring = _getopt_initialize (argc, argv, optstring, + posixly_correct, d); + d->__initialized = 1; + } + + /* Test whether ARGV[optind] points to a non-option argument. + Either it does not have option syntax, or there is an environment flag + from the shell indicating it is not an option. The later information + is only used when the used in the GNU libc. */ +#if defined _LIBC && defined USE_NONOPTION_FLAGS +# define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \ + || (d->optind < d->__nonoption_flags_len \ + && __getopt_nonoption_flags[d->optind] == '1')) +#else +# define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0') +#endif + + if (d->__nextchar == NULL || *d->__nextchar == '\0') + { + /* Advance to the next ARGV-element. */ + + /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been + moved back by the user (who may also have changed the arguments). */ + if (d->__last_nonopt > d->optind) + d->__last_nonopt = d->optind; + if (d->__first_nonopt > d->optind) + d->__first_nonopt = d->optind; + + if (d->__ordering == PERMUTE) + { + /* If we have just processed some options following some non-options, + exchange them so that the options come first. */ + + if (d->__first_nonopt != d->__last_nonopt + && d->__last_nonopt != d->optind) + exchange ((char **) argv, d); + else if (d->__last_nonopt != d->optind) + d->__first_nonopt = d->optind; + + /* Skip any additional non-options + and extend the range of non-options previously skipped. */ + + while (d->optind < argc && NONOPTION_P) + d->optind++; + d->__last_nonopt = d->optind; + } + + /* The special ARGV-element `--' means premature end of options. + Skip it like a null option, + then exchange with previous non-options as if it were an option, + then skip everything else like a non-option. */ + + if (d->optind != argc && !strcmp (argv[d->optind], "--")) + { + d->optind++; + + if (d->__first_nonopt != d->__last_nonopt + && d->__last_nonopt != d->optind) + exchange ((char **) argv, d); + else if (d->__first_nonopt == d->__last_nonopt) + d->__first_nonopt = d->optind; + d->__last_nonopt = argc; + + d->optind = argc; + } + + /* If we have done all the ARGV-elements, stop the scan + and back over any non-options that we skipped and permuted. */ + + if (d->optind == argc) + { + /* Set the next-arg-index to point at the non-options + that we previously skipped, so the caller will digest them. */ + if (d->__first_nonopt != d->__last_nonopt) + d->optind = d->__first_nonopt; + return -1; + } + + /* If we have come to a non-option and did not permute it, + either stop the scan or describe it to the caller and pass it by. */ + + if (NONOPTION_P) + { + if (d->__ordering == REQUIRE_ORDER) + return -1; + d->optarg = argv[d->optind++]; + return 1; + } + + /* We have found another option-ARGV-element. + Skip the initial punctuation. */ + + d->__nextchar = (argv[d->optind] + 1 + + (longopts != NULL && argv[d->optind][1] == '-')); + } + + /* Decode the current option-ARGV-element. */ + + /* Check whether the ARGV-element is a long option. + + If long_only and the ARGV-element has the form "-f", where f is + a valid short option, don't consider it an abbreviated form of + a long option that starts with f. Otherwise there would be no + way to give the -f short option. + + On the other hand, if there's a long option "fubar" and + the ARGV-element is "-fu", do consider that an abbreviation of + the long option, just like "--fu", and not "-f" with arg "u". + + This distinction seems to be the most useful approach. */ + + if (longopts != NULL + && (argv[d->optind][1] == '-' + || (long_only && (argv[d->optind][2] + || !strchr (optstring, argv[d->optind][1]))))) + { + char *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = -1; + int option_index; + + for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++) + /* Do nothing. */ ; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar)) + { + if ((unsigned int) (nameend - d->__nextchar) + == (unsigned int) strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else if (long_only + || pfound->has_arg != p->has_arg + || pfound->flag != p->flag + || pfound->val != p->val) + /* Second or later nonexact match found. */ + ambig = 1; + } + + if (ambig && !exact) + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"), + argv[0], argv[d->optind]) >= 0) + { + _IO_flockfile (stderr); + + int old_flags2 = ((_IO_FILE *) stderr)->_flags2; + ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; + + __fxprintf (NULL, "%s", buf); + + ((_IO_FILE *) stderr)->_flags2 = old_flags2; + _IO_funlockfile (stderr); + + free (buf); + } +#else + fprintf (stderr, _("%s: option `%s' is ambiguous\n"), + argv[0], argv[d->optind]); +#endif + } + d->__nextchar += strlen (d->__nextchar); + d->optind++; + d->optopt = 0; + return '?'; + } + + if (pfound != NULL) + { + option_index = indfound; + d->optind++; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + d->optarg = nameend + 1; + else + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + int n; +#endif + + if (argv[d->optind - 1][1] == '-') + { + /* --option */ +#if defined _LIBC && defined USE_IN_LIBIO + n = __asprintf (&buf, _("\ +%s: option `--%s' doesn't allow an argument\n"), + argv[0], pfound->name); +#else + fprintf (stderr, _("\ +%s: option `--%s' doesn't allow an argument\n"), + argv[0], pfound->name); +#endif + } + else + { + /* +option or -option */ +#if defined _LIBC && defined USE_IN_LIBIO + n = __asprintf (&buf, _("\ +%s: option `%c%s' doesn't allow an argument\n"), + argv[0], argv[d->optind - 1][0], + pfound->name); +#else + fprintf (stderr, _("\ +%s: option `%c%s' doesn't allow an argument\n"), + argv[0], argv[d->optind - 1][0], + pfound->name); +#endif + } + +#if defined _LIBC && defined USE_IN_LIBIO + if (n >= 0) + { + _IO_flockfile (stderr); + + int old_flags2 = ((_IO_FILE *) stderr)->_flags2; + ((_IO_FILE *) stderr)->_flags2 + |= _IO_FLAGS2_NOTCANCEL; + + __fxprintf (NULL, "%s", buf); + + ((_IO_FILE *) stderr)->_flags2 = old_flags2; + _IO_funlockfile (stderr); + + free (buf); + } +#endif + } + + d->__nextchar += strlen (d->__nextchar); + + d->optopt = pfound->val; + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (d->optind < argc) + d->optarg = argv[d->optind++]; + else + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + if (__asprintf (&buf, _("\ +%s: option `%s' requires an argument\n"), + argv[0], argv[d->optind - 1]) >= 0) + { + _IO_flockfile (stderr); + + int old_flags2 = ((_IO_FILE *) stderr)->_flags2; + ((_IO_FILE *) stderr)->_flags2 + |= _IO_FLAGS2_NOTCANCEL; + + __fxprintf (NULL, "%s", buf); + + ((_IO_FILE *) stderr)->_flags2 = old_flags2; + _IO_funlockfile (stderr); + + free (buf); + } +#else + fprintf (stderr, + _("%s: option `%s' requires an argument\n"), + argv[0], argv[d->optind - 1]); +#endif + } + d->__nextchar += strlen (d->__nextchar); + d->optopt = pfound->val; + return optstring[0] == ':' ? ':' : '?'; + } + } + d->__nextchar += strlen (d->__nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + + /* Can't find it as a long option. If this is not getopt_long_only, + or the option starts with '--' or is not a valid short + option, then it's an error. + Otherwise interpret it as a short option. */ + if (!long_only || argv[d->optind][1] == '-' + || strchr (optstring, *d->__nextchar) == NULL) + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + int n; +#endif + + if (argv[d->optind][1] == '-') + { + /* --option */ +#if defined _LIBC && defined USE_IN_LIBIO + n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"), + argv[0], d->__nextchar); +#else + fprintf (stderr, _("%s: unrecognized option `--%s'\n"), + argv[0], d->__nextchar); +#endif + } + else + { + /* +option or -option */ +#if defined _LIBC && defined USE_IN_LIBIO + n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"), + argv[0], argv[d->optind][0], d->__nextchar); +#else + fprintf (stderr, _("%s: unrecognized option `%c%s'\n"), + argv[0], argv[d->optind][0], d->__nextchar); +#endif + } + +#if defined _LIBC && defined USE_IN_LIBIO + if (n >= 0) + { + _IO_flockfile (stderr); + + int old_flags2 = ((_IO_FILE *) stderr)->_flags2; + ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; + + __fxprintf (NULL, "%s", buf); + + ((_IO_FILE *) stderr)->_flags2 = old_flags2; + _IO_funlockfile (stderr); + + free (buf); + } +#endif + } + d->__nextchar = (char *) ""; + d->optind++; + d->optopt = 0; + return '?'; + } + } + + /* Look at and handle the next short option-character. */ + + { + char c = *d->__nextchar++; + char *temp = strchr (optstring, c); + + /* Increment `optind' when we start to process its last character. */ + if (*d->__nextchar == '\0') + ++d->optind; + + if (temp == NULL || c == ':') + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + int n; +#endif + + if (d->__posixly_correct) + { + /* 1003.2 specifies the format of this message. */ +#if defined _LIBC && defined USE_IN_LIBIO + n = __asprintf (&buf, _("%s: illegal option -- %c\n"), + argv[0], c); +#else + fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c); +#endif + } + else + { +#if defined _LIBC && defined USE_IN_LIBIO + n = __asprintf (&buf, _("%s: invalid option -- %c\n"), + argv[0], c); +#else + fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c); +#endif + } + +#if defined _LIBC && defined USE_IN_LIBIO + if (n >= 0) + { + _IO_flockfile (stderr); + + int old_flags2 = ((_IO_FILE *) stderr)->_flags2; + ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; + + __fxprintf (NULL, "%s", buf); + + ((_IO_FILE *) stderr)->_flags2 = old_flags2; + _IO_funlockfile (stderr); + + free (buf); + } +#endif + } + d->optopt = c; + return '?'; + } + /* Convenience. Treat POSIX -W foo same as long option --foo */ + if (temp[0] == 'W' && temp[1] == ';') + { + char *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = 0; + int option_index; + + /* This is an option that requires an argument. */ + if (*d->__nextchar != '\0') + { + d->optarg = d->__nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + d->optind++; + } + else if (d->optind == argc) + { + if (print_errors) + { + /* 1003.2 specifies the format of this message. */ +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + if (__asprintf (&buf, + _("%s: option requires an argument -- %c\n"), + argv[0], c) >= 0) + { + _IO_flockfile (stderr); + + int old_flags2 = ((_IO_FILE *) stderr)->_flags2; + ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; + + __fxprintf (NULL, "%s", buf); + + ((_IO_FILE *) stderr)->_flags2 = old_flags2; + _IO_funlockfile (stderr); + + free (buf); + } +#else + fprintf (stderr, _("%s: option requires an argument -- %c\n"), + argv[0], c); +#endif + } + d->optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + return c; + } + else + /* We already incremented `d->optind' once; + increment it again when taking next ARGV-elt as argument. */ + d->optarg = argv[d->optind++]; + + /* optarg is now the argument, see if it's in the + table of longopts. */ + + for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '='; + nameend++) + /* Do nothing. */ ; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar)) + { + if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else + /* Second or later nonexact match found. */ + ambig = 1; + } + if (ambig && !exact) + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"), + argv[0], argv[d->optind]) >= 0) + { + _IO_flockfile (stderr); + + int old_flags2 = ((_IO_FILE *) stderr)->_flags2; + ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; + + __fxprintf (NULL, "%s", buf); + + ((_IO_FILE *) stderr)->_flags2 = old_flags2; + _IO_funlockfile (stderr); + + free (buf); + } +#else + fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"), + argv[0], argv[d->optind]); +#endif + } + d->__nextchar += strlen (d->__nextchar); + d->optind++; + return '?'; + } + if (pfound != NULL) + { + option_index = indfound; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + d->optarg = nameend + 1; + else + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + if (__asprintf (&buf, _("\ +%s: option `-W %s' doesn't allow an argument\n"), + argv[0], pfound->name) >= 0) + { + _IO_flockfile (stderr); + + int old_flags2 = ((_IO_FILE *) stderr)->_flags2; + ((_IO_FILE *) stderr)->_flags2 + |= _IO_FLAGS2_NOTCANCEL; + + __fxprintf (NULL, "%s", buf); + + ((_IO_FILE *) stderr)->_flags2 = old_flags2; + _IO_funlockfile (stderr); + + free (buf); + } +#else + fprintf (stderr, _("\ +%s: option `-W %s' doesn't allow an argument\n"), + argv[0], pfound->name); +#endif + } + + d->__nextchar += strlen (d->__nextchar); + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (d->optind < argc) + d->optarg = argv[d->optind++]; + else + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + if (__asprintf (&buf, _("\ +%s: option `%s' requires an argument\n"), + argv[0], argv[d->optind - 1]) >= 0) + { + _IO_flockfile (stderr); + + int old_flags2 = ((_IO_FILE *) stderr)->_flags2; + ((_IO_FILE *) stderr)->_flags2 + |= _IO_FLAGS2_NOTCANCEL; + + __fxprintf (NULL, "%s", buf); + + ((_IO_FILE *) stderr)->_flags2 = old_flags2; + _IO_funlockfile (stderr); + + free (buf); + } +#else + fprintf (stderr, + _("%s: option `%s' requires an argument\n"), + argv[0], argv[d->optind - 1]); +#endif + } + d->__nextchar += strlen (d->__nextchar); + return optstring[0] == ':' ? ':' : '?'; + } + } + d->__nextchar += strlen (d->__nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + d->__nextchar = NULL; + return 'W'; /* Let the application handle it. */ + } + if (temp[1] == ':') + { + if (temp[2] == ':') + { + /* This is an option that accepts an argument optionally. */ + if (*d->__nextchar != '\0') + { + d->optarg = d->__nextchar; + d->optind++; + } + else + d->optarg = NULL; + d->__nextchar = NULL; + } + else + { + /* This is an option that requires an argument. */ + if (*d->__nextchar != '\0') + { + d->optarg = d->__nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + d->optind++; + } + else if (d->optind == argc) + { + if (print_errors) + { + /* 1003.2 specifies the format of this message. */ +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + if (__asprintf (&buf, _("\ +%s: option requires an argument -- %c\n"), + argv[0], c) >= 0) + { + _IO_flockfile (stderr); + + int old_flags2 = ((_IO_FILE *) stderr)->_flags2; + ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; + + __fxprintf (NULL, "%s", buf); + + ((_IO_FILE *) stderr)->_flags2 = old_flags2; + _IO_funlockfile (stderr); + + free (buf); + } +#else + fprintf (stderr, + _("%s: option requires an argument -- %c\n"), + argv[0], c); +#endif + } + d->optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + } + else + /* We already incremented `optind' once; + increment it again when taking next ARGV-elt as argument. */ + d->optarg = argv[d->optind++]; + d->__nextchar = NULL; + } + } + return c; + } +} + +int +_getopt_internal (int argc, char **argv, const char *optstring, + const struct option *longopts, int *longind, + int long_only, int posixly_correct) +{ + int result; + + getopt_data.optind = optind; + getopt_data.opterr = opterr; + + result = _getopt_internal_r (argc, argv, optstring, longopts, longind, + long_only, posixly_correct, &getopt_data); + + optind = getopt_data.optind; + optarg = getopt_data.optarg; + optopt = getopt_data.optopt; + + return result; +} + +/* glibc gets a LSB-compliant getopt. + Standalone applications get a POSIX-compliant getopt. */ +#if _LIBC +enum { POSIXLY_CORRECT = 0 }; +#else +enum { POSIXLY_CORRECT = 1 }; +#endif + +int +getopt (int argc, char *const *argv, const char *optstring) +{ + return _getopt_internal (argc, (char **) argv, optstring, NULL, NULL, 0, + POSIXLY_CORRECT); +} + + +#ifdef TEST + +/* Compile with -DTEST to make an executable for use in testing + the above definition of `getopt'. */ + +int +main (int argc, char **argv) +{ + int c; + int digit_optind = 0; + + while (1) + { + int this_option_optind = optind ? optind : 1; + + c = getopt (argc, argv, "abc:d:0123456789"); + if (c == -1) + break; + + switch (c) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (digit_optind != 0 && digit_optind != this_option_optind) + printf ("digits occur in two different argv-elements.\n"); + digit_optind = this_option_optind; + printf ("option %c\n", c); + break; + + case 'a': + printf ("option a\n"); + break; + + case 'b': + printf ("option b\n"); + break; + + case 'c': + printf ("option c with value `%s'\n", optarg); + break; + + case '?': + break; + + default: + printf ("?? getopt returned character code 0%o ??\n", c); + } + } + + if (optind < argc) + { + printf ("non-option ARGV-elements: "); + while (optind < argc) + printf ("%s ", argv[optind++]); + printf ("\n"); + } + + exit (0); +} + +#endif /* TEST */ diff --git a/src/bin/findutils/gnulib/lib/getopt.in.h b/src/bin/findutils/gnulib/lib/getopt.in.h new file mode 100644 index 0000000000..d2d3e6e63b --- /dev/null +++ b/src/bin/findutils/gnulib/lib/getopt.in.h @@ -0,0 +1,225 @@ +/* Declarations for getopt. + Copyright (C) 1989-1994,1996-1999,2001,2003,2004,2005,2006,2007 + Free Software Foundation, Inc. + This file is part of the GNU C Library. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef _GETOPT_H + +#ifndef __need_getopt +# define _GETOPT_H 1 +#endif + +/* Standalone applications should #define __GETOPT_PREFIX to an + identifier that prefixes the external functions and variables + defined in this header. When this happens, include the + headers that might declare getopt so that they will not cause + confusion if included after this file. Then systematically rename + identifiers so that they do not collide with the system functions + and variables. Renaming avoids problems with some compilers and + linkers. */ +#if defined __GETOPT_PREFIX && !defined __need_getopt +# include +# include +# include +# undef __need_getopt +# undef getopt +# undef getopt_long +# undef getopt_long_only +# undef optarg +# undef opterr +# undef optind +# undef optopt +# define __GETOPT_CONCAT(x, y) x ## y +# define __GETOPT_XCONCAT(x, y) __GETOPT_CONCAT (x, y) +# define __GETOPT_ID(y) __GETOPT_XCONCAT (__GETOPT_PREFIX, y) +# define getopt __GETOPT_ID (getopt) +# define getopt_long __GETOPT_ID (getopt_long) +# define getopt_long_only __GETOPT_ID (getopt_long_only) +# define optarg __GETOPT_ID (optarg) +# define opterr __GETOPT_ID (opterr) +# define optind __GETOPT_ID (optind) +# define optopt __GETOPT_ID (optopt) +#endif + +/* Standalone applications get correct prototypes for getopt_long and + getopt_long_only; they declare "char **argv". libc uses prototypes + with "char *const *argv" that are incorrect because getopt_long and + getopt_long_only can permute argv; this is required for backward + compatibility (e.g., for LSB 2.0.1). + + This used to be `#if defined __GETOPT_PREFIX && !defined __need_getopt', + but it caused redefinition warnings if both unistd.h and getopt.h were + included, since unistd.h includes getopt.h having previously defined + __need_getopt. + + The only place where __getopt_argv_const is used is in definitions + of getopt_long and getopt_long_only below, but these are visible + only if __need_getopt is not defined, so it is quite safe to rewrite + the conditional as follows: +*/ +#if !defined __need_getopt +# if defined __GETOPT_PREFIX +# define __getopt_argv_const /* empty */ +# else +# define __getopt_argv_const const +# endif +#endif + +/* If __GNU_LIBRARY__ is not already defined, either we are being used + standalone, or this is the first header included in the source file. + If we are being used with glibc, we need to include , but + that does not exist if we are standalone. So: if __GNU_LIBRARY__ is + not defined, include , which will pull in for us + if it's from glibc. (Why ctype.h? It's guaranteed to exist and it + doesn't flood the namespace with stuff the way some other headers do.) */ +#if !defined __GNU_LIBRARY__ +# include +#endif + +#ifndef __THROW +# ifndef __GNUC_PREREQ +# define __GNUC_PREREQ(maj, min) (0) +# endif +# if defined __cplusplus && __GNUC_PREREQ (2,8) +# define __THROW throw () +# else +# define __THROW +# endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* For communication from `getopt' to the caller. + When `getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + +extern char *optarg; + +/* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `getopt'. + + On entry to `getopt', zero means this is the first call; initialize. + + When `getopt' returns -1, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + +extern int optind; + +/* Callers store zero here to inhibit the error message `getopt' prints + for unrecognized options. */ + +extern int opterr; + +/* Set to an option character which was unrecognized. */ + +extern int optopt; + +#ifndef __need_getopt +/* Describe the long-named options requested by the application. + The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector + of `struct option' terminated by an element containing a name which is + zero. + + The field `has_arg' is: + no_argument (or 0) if the option does not take an argument, + required_argument (or 1) if the option requires an argument, + optional_argument (or 2) if the option takes an optional argument. + + If the field `flag' is not NULL, it points to a variable that is set + to the value given in the field `val' when the option is found, but + left unchanged if the option is not found. + + To have a long-named option do something other than set an `int' to + a compiled-in constant, such as set a value from `optarg', set the + option's `flag' field to zero and its `val' field to a nonzero + value (the equivalent single-letter option character, if there is + one). For long options that have a zero `flag' field, `getopt' + returns the contents of the `val' field. */ + +struct option +{ + const char *name; + /* has_arg can't be an enum because some compilers complain about + type mismatches in all the code that assumes it is an int. */ + int has_arg; + int *flag; + int val; +}; + +/* Names for the values of the `has_arg' field of `struct option'. */ + +# define no_argument 0 +# define required_argument 1 +# define optional_argument 2 +#endif /* need getopt */ + + +/* Get definitions and prototypes for functions to process the + arguments in ARGV (ARGC of them, minus the program name) for + options given in OPTS. + + Return the option character from OPTS just read. Return -1 when + there are no more options. For unrecognized options, or options + missing arguments, `optopt' is set to the option letter, and '?' is + returned. + + The OPTS string is a list of characters which are recognized option + letters, optionally followed by colons, specifying that that letter + takes an argument, to be placed in `optarg'. + + If a letter in OPTS is followed by two colons, its argument is + optional. This behavior is specific to the GNU `getopt'. + + The argument `--' causes premature termination of argument + scanning, explicitly telling `getopt' that there are no more + options. + + If OPTS begins with `-', then non-option arguments are treated as + arguments to the option '\1'. This behavior is specific to the GNU + `getopt'. If OPTS begins with `+', or POSIXLY_CORRECT is set in + the environment, then do not permute arguments. */ + +extern int getopt (int ___argc, char *const *___argv, const char *__shortopts) + __THROW; + +#ifndef __need_getopt +extern int getopt_long (int ___argc, char *__getopt_argv_const *___argv, + const char *__shortopts, + const struct option *__longopts, int *__longind) + __THROW; +extern int getopt_long_only (int ___argc, char *__getopt_argv_const *___argv, + const char *__shortopts, + const struct option *__longopts, int *__longind) + __THROW; + +#endif + +#ifdef __cplusplus +} +#endif + +/* Make sure we later can get all the definitions and declarations. */ +#undef __need_getopt + +#endif /* getopt.h */ diff --git a/src/bin/findutils/lib/getopt1.c b/src/bin/findutils/gnulib/lib/getopt1.c similarity index 55% rename from src/bin/findutils/lib/getopt1.c rename to src/bin/findutils/gnulib/lib/getopt1.c index 4580211cfa..d6a3ecf4e7 100644 --- a/src/bin/findutils/lib/getopt1.c +++ b/src/bin/findutils/gnulib/lib/getopt1.c @@ -1,11 +1,12 @@ /* getopt_long and getopt_long_only entry points for GNU getopt. - Copyright (C) 1987, 88, 89, 90, 91, 92, 1993, 1994 - Free Software Foundation, Inc. + Copyright (C) 1987,88,89,90,91,92,93,94,96,97,98,2004,2006 + Free Software Foundation, Inc. + This file is part of the GNU C Library. - This program is free software; you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by the - Free Software Foundation; either version 2, or (at your option) any - later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -13,42 +14,22 @@ GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . */ -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "getopt.h" - -#if !defined (__STDC__) || !__STDC__ -/* This is a separate conditional since some stdc systems - reject `defined (const)'. */ -#ifndef const -#define const -#endif +#ifdef _LIBC +# include +#else +# include +# include "getopt.h" #endif +#include "getopt_int.h" #include -/* Comment out all this code if we are using the GNU C Library, and are not - actually compiling the library itself. This code is part of the GNU C - Library, but also included in many other GNU distributions. Compiling - and linking in this code is a waste when using the GNU C library - (especially if it is a shared library). Rather than having every GNU - program understand `configure --with-gnu-libc' and omit the object files, - it is simpler to just do this in the source for each such file. */ - -#if defined (_LIBC) || !defined (__GNU_LIBRARY__) - - /* This needs to come after some library #include to get __GNU_LIBRARY__ defined. */ #ifdef __GNU_LIBRARY__ #include -#else -char *getenv (); #endif #ifndef NULL @@ -56,14 +37,20 @@ char *getenv (); #endif int -getopt_long (argc, argv, options, long_options, opt_index) - int argc; - char *const *argv; - const char *options; - const struct option *long_options; - int *opt_index; +getopt_long (int argc, char *__getopt_argv_const *argv, const char *options, + const struct option *long_options, int *opt_index) { - return _getopt_internal (argc, argv, options, long_options, opt_index, 0); + return _getopt_internal (argc, (char **) argv, options, long_options, + opt_index, 0, 0); +} + +int +_getopt_long_r (int argc, char **argv, const char *options, + const struct option *long_options, int *opt_index, + struct _getopt_data *d) +{ + return _getopt_internal_r (argc, argv, options, long_options, opt_index, + 0, 0, d); } /* Like getopt_long, but '-' as well as '--' can indicate a long option. @@ -72,27 +59,30 @@ getopt_long (argc, argv, options, long_options, opt_index) instead. */ int -getopt_long_only (argc, argv, options, long_options, opt_index) - int argc; - char *const *argv; - const char *options; - const struct option *long_options; - int *opt_index; +getopt_long_only (int argc, char *__getopt_argv_const *argv, + const char *options, + const struct option *long_options, int *opt_index) { - return _getopt_internal (argc, argv, options, long_options, opt_index, 1); + return _getopt_internal (argc, (char **) argv, options, long_options, + opt_index, 1, 0); } +int +_getopt_long_only_r (int argc, char **argv, const char *options, + const struct option *long_options, int *opt_index, + struct _getopt_data *d) +{ + return _getopt_internal_r (argc, argv, options, long_options, opt_index, + 1, 0, d); +} -#endif /* _LIBC or not __GNU_LIBRARY__. */ #ifdef TEST #include int -main (argc, argv) - int argc; - char **argv; +main (int argc, char **argv) { int c; int digit_optind = 0; @@ -114,7 +104,7 @@ main (argc, argv) c = getopt_long (argc, argv, "abc:d:0123456789", long_options, &option_index); - if (c == EOF) + if (c == -1) break; switch (c) diff --git a/src/bin/findutils/gnulib/lib/getopt_int.h b/src/bin/findutils/gnulib/lib/getopt_int.h new file mode 100644 index 0000000000..3c6628bb94 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/getopt_int.h @@ -0,0 +1,130 @@ +/* Internal declarations for getopt. + Copyright (C) 1989-1994,1996-1999,2001,2003,2004 + Free Software Foundation, Inc. + This file is part of the GNU C Library. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef _GETOPT_INT_H +#define _GETOPT_INT_H 1 + +extern int _getopt_internal (int ___argc, char **___argv, + const char *__shortopts, + const struct option *__longopts, int *__longind, + int __long_only, int __posixly_correct); + + +/* Reentrant versions which can handle parsing multiple argument + vectors at the same time. */ + +/* Data type for reentrant functions. */ +struct _getopt_data +{ + /* These have exactly the same meaning as the corresponding global + variables, except that they are used for the reentrant + versions of getopt. */ + int optind; + int opterr; + int optopt; + char *optarg; + + /* Internal members. */ + + /* True if the internal members have been initialized. */ + int __initialized; + + /* The next char to be scanned in the option-element + in which the last option character we returned was found. + This allows us to pick up the scan where we left off. + + If this is zero, or a null string, it means resume the scan + by advancing to the next ARGV-element. */ + char *__nextchar; + + /* Describe how to deal with options that follow non-option ARGV-elements. + + If the caller did not specify anything, + the default is REQUIRE_ORDER if the environment variable + POSIXLY_CORRECT is defined, PERMUTE otherwise. + + REQUIRE_ORDER means don't recognize them as options; + stop option processing when the first non-option is seen. + This is what Unix does. + This mode of operation is selected by either setting the environment + variable POSIXLY_CORRECT, or using `+' as the first character + of the list of option characters, or by calling getopt. + + PERMUTE is the default. We permute the contents of ARGV as we + scan, so that eventually all the non-options are at the end. + This allows options to be given in any order, even with programs + that were not written to expect this. + + RETURN_IN_ORDER is an option available to programs that were + written to expect options and other ARGV-elements in any order + and that care about the ordering of the two. We describe each + non-option ARGV-element as if it were the argument of an option + with character code 1. Using `-' as the first character of the + list of option characters selects this mode of operation. + + The special argument `--' forces an end of option-scanning regardless + of the value of `ordering'. In the case of RETURN_IN_ORDER, only + `--' can cause `getopt' to return -1 with `optind' != ARGC. */ + + enum + { + REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER + } __ordering; + + /* If the POSIXLY_CORRECT environment variable is set + or getopt was called. */ + int __posixly_correct; + + + /* Handle permutation of arguments. */ + + /* Describe the part of ARGV that contains non-options that have + been skipped. `first_nonopt' is the index in ARGV of the first + of them; `last_nonopt' is the index after the last of them. */ + + int __first_nonopt; + int __last_nonopt; + +#if defined _LIBC && defined USE_NONOPTION_FLAGS + int __nonoption_flags_max_len; + int __nonoption_flags_len; +# endif +}; + +/* The initializer is necessary to set OPTIND and OPTERR to their + default values and to clear the initialization flag. */ +#define _GETOPT_DATA_INITIALIZER { 1, 1 } + +extern int _getopt_internal_r (int ___argc, char **___argv, + const char *__shortopts, + const struct option *__longopts, int *__longind, + int __long_only, int __posixly_correct, + struct _getopt_data *__data); + +extern int _getopt_long_r (int ___argc, char **___argv, + const char *__shortopts, + const struct option *__longopts, int *__longind, + struct _getopt_data *__data); + +extern int _getopt_long_only_r (int ___argc, char **___argv, + const char *__shortopts, + const struct option *__longopts, + int *__longind, + struct _getopt_data *__data); + +#endif /* getopt_int.h */ diff --git a/src/bin/findutils/gnulib/lib/gettext.h b/src/bin/findutils/gnulib/lib/gettext.h new file mode 100644 index 0000000000..763dd3c147 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/gettext.h @@ -0,0 +1,270 @@ +/* Convenience header for conditional use of GNU . + Copyright (C) 1995-1998, 2000-2002, 2004-2006 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _LIBGETTEXT_H +#define _LIBGETTEXT_H 1 + +/* NLS can be disabled through the configure --disable-nls option. */ +#if ENABLE_NLS + +/* Get declarations of GNU message catalog functions. */ +# include + +/* You can set the DEFAULT_TEXT_DOMAIN macro to specify the domain used by + the gettext() and ngettext() macros. This is an alternative to calling + textdomain(), and is useful for libraries. */ +# ifdef DEFAULT_TEXT_DOMAIN +# undef gettext +# define gettext(Msgid) \ + dgettext (DEFAULT_TEXT_DOMAIN, Msgid) +# undef ngettext +# define ngettext(Msgid1, Msgid2, N) \ + dngettext (DEFAULT_TEXT_DOMAIN, Msgid1, Msgid2, N) +# endif + +#else + +/* Solaris /usr/include/locale.h includes /usr/include/libintl.h, which + chokes if dcgettext is defined as a macro. So include it now, to make + later inclusions of a NOP. We don't include + as well because people using "gettext.h" will not include , + and also including would fail on SunOS 4, whereas + is OK. */ +#if defined(__sun) +# include +#endif + +/* Many header files from the libstdc++ coming with g++ 3.3 or newer include + , which chokes if dcgettext is defined as a macro. So include + it now, to make later inclusions of a NOP. */ +#if defined(__cplusplus) && defined(__GNUG__) && (__GNUC__ >= 3) +# include +# if (__GLIBC__ >= 2) || _GLIBCXX_HAVE_LIBINTL_H +# include +# endif +#endif + +/* Disabled NLS. + The casts to 'const char *' serve the purpose of producing warnings + for invalid uses of the value returned from these functions. + On pre-ANSI systems without 'const', the config.h file is supposed to + contain "#define const". */ +# define gettext(Msgid) ((const char *) (Msgid)) +# define dgettext(Domainname, Msgid) ((void) (Domainname), gettext (Msgid)) +# define dcgettext(Domainname, Msgid, Category) \ + ((void) (Category), dgettext (Domainname, Msgid)) +# define ngettext(Msgid1, Msgid2, N) \ + ((N) == 1 \ + ? ((void) (Msgid2), (const char *) (Msgid1)) \ + : ((void) (Msgid1), (const char *) (Msgid2))) +# define dngettext(Domainname, Msgid1, Msgid2, N) \ + ((void) (Domainname), ngettext (Msgid1, Msgid2, N)) +# define dcngettext(Domainname, Msgid1, Msgid2, N, Category) \ + ((void) (Category), dngettext(Domainname, Msgid1, Msgid2, N)) +# define textdomain(Domainname) ((const char *) (Domainname)) +# define bindtextdomain(Domainname, Dirname) \ + ((void) (Domainname), (const char *) (Dirname)) +# define bind_textdomain_codeset(Domainname, Codeset) \ + ((void) (Domainname), (const char *) (Codeset)) + +#endif + +/* A pseudo function call that serves as a marker for the automated + extraction of messages, but does not call gettext(). The run-time + translation is done at a different place in the code. + The argument, String, should be a literal string. Concatenated strings + and other string expressions won't work. + The macro's expansion is not parenthesized, so that it is suitable as + initializer for static 'char[]' or 'const char[]' variables. */ +#define gettext_noop(String) String + +/* The separator between msgctxt and msgid in a .mo file. */ +#define GETTEXT_CONTEXT_GLUE "\004" + +/* Pseudo function calls, taking a MSGCTXT and a MSGID instead of just a + MSGID. MSGCTXT and MSGID must be string literals. MSGCTXT should be + short and rarely need to change. + The letter 'p' stands for 'particular' or 'special'. */ +#ifdef DEFAULT_TEXT_DOMAIN +# define pgettext(Msgctxt, Msgid) \ + pgettext_aux (DEFAULT_TEXT_DOMAIN, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, LC_MESSAGES) +#else +# define pgettext(Msgctxt, Msgid) \ + pgettext_aux (NULL, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, LC_MESSAGES) +#endif +#define dpgettext(Domainname, Msgctxt, Msgid) \ + pgettext_aux (Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, LC_MESSAGES) +#define dcpgettext(Domainname, Msgctxt, Msgid, Category) \ + pgettext_aux (Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, Category) +#ifdef DEFAULT_TEXT_DOMAIN +# define npgettext(Msgctxt, Msgid, MsgidPlural, N) \ + npgettext_aux (DEFAULT_TEXT_DOMAIN, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, LC_MESSAGES) +#else +# define npgettext(Msgctxt, Msgid, MsgidPlural, N) \ + npgettext_aux (NULL, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, LC_MESSAGES) +#endif +#define dnpgettext(Domainname, Msgctxt, Msgid, MsgidPlural, N) \ + npgettext_aux (Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, LC_MESSAGES) +#define dcnpgettext(Domainname, Msgctxt, Msgid, MsgidPlural, N, Category) \ + npgettext_aux (Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, Category) + +#ifdef __GNUC__ +__inline +#else +#ifdef __cplusplus +inline +#endif +#endif +static const char * +pgettext_aux (const char *domain, + const char *msg_ctxt_id, const char *msgid, + int category) +{ + const char *translation = dcgettext (domain, msg_ctxt_id, category); + if (translation == msg_ctxt_id) + return msgid; + else + return translation; +} + +#ifdef __GNUC__ +__inline +#else +#ifdef __cplusplus +inline +#endif +#endif +static const char * +npgettext_aux (const char *domain, + const char *msg_ctxt_id, const char *msgid, + const char *msgid_plural, unsigned long int n, + int category) +{ + const char *translation = + dcngettext (domain, msg_ctxt_id, msgid_plural, n, category); + if (translation == msg_ctxt_id || translation == msgid_plural) + return (n == 1 ? msgid : msgid_plural); + else + return translation; +} + +/* The same thing extended for non-constant arguments. Here MSGCTXT and MSGID + can be arbitrary expressions. But for string literals these macros are + less efficient than those above. */ + +#include + +#define _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS \ + (((__GNUC__ >= 3 || __GNUG__ >= 2) && !__STRICT_ANSI__) \ + /* || __STDC_VERSION__ >= 199901L */ ) + +#if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS +#include +#endif + +#define pgettext_expr(Msgctxt, Msgid) \ + dcpgettext_expr (NULL, Msgctxt, Msgid, LC_MESSAGES) +#define dpgettext_expr(Domainname, Msgctxt, Msgid) \ + dcpgettext_expr (Domainname, Msgctxt, Msgid, LC_MESSAGES) + +#ifdef __GNUC__ +__inline +#else +#ifdef __cplusplus +inline +#endif +#endif +static const char * +dcpgettext_expr (const char *domain, + const char *msgctxt, const char *msgid, + int category) +{ + size_t msgctxt_len = strlen (msgctxt) + 1; + size_t msgid_len = strlen (msgid) + 1; + const char *translation; +#if _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS + char msg_ctxt_id[msgctxt_len + msgid_len]; +#else + char buf[1024]; + char *msg_ctxt_id = + (msgctxt_len + msgid_len <= sizeof (buf) + ? buf + : (char *) malloc (msgctxt_len + msgid_len)); + if (msg_ctxt_id != NULL) +#endif + { + memcpy (msg_ctxt_id, msgctxt, msgctxt_len - 1); + msg_ctxt_id[msgctxt_len - 1] = '\004'; + memcpy (msg_ctxt_id + msgctxt_len, msgid, msgid_len); + translation = dcgettext (domain, msg_ctxt_id, category); +#if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS + if (msg_ctxt_id != buf) + free (msg_ctxt_id); +#endif + if (translation != msg_ctxt_id) + return translation; + } + return msgid; +} + +#define npgettext_expr(Msgctxt, Msgid, MsgidPlural, N) \ + dcnpgettext_expr (NULL, Msgctxt, Msgid, MsgidPlural, N, LC_MESSAGES) +#define dnpgettext_expr(Domainname, Msgctxt, Msgid, MsgidPlural, N) \ + dcnpgettext_expr (Domainname, Msgctxt, Msgid, MsgidPlural, N, LC_MESSAGES) + +#ifdef __GNUC__ +__inline +#else +#ifdef __cplusplus +inline +#endif +#endif +static const char * +dcnpgettext_expr (const char *domain, + const char *msgctxt, const char *msgid, + const char *msgid_plural, unsigned long int n, + int category) +{ + size_t msgctxt_len = strlen (msgctxt) + 1; + size_t msgid_len = strlen (msgid) + 1; + const char *translation; +#if _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS + char msg_ctxt_id[msgctxt_len + msgid_len]; +#else + char buf[1024]; + char *msg_ctxt_id = + (msgctxt_len + msgid_len <= sizeof (buf) + ? buf + : (char *) malloc (msgctxt_len + msgid_len)); + if (msg_ctxt_id != NULL) +#endif + { + memcpy (msg_ctxt_id, msgctxt, msgctxt_len - 1); + msg_ctxt_id[msgctxt_len - 1] = '\004'; + memcpy (msg_ctxt_id + msgctxt_len, msgid, msgid_len); + translation = dcngettext (domain, msg_ctxt_id, msgid_plural, n, category); +#if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS + if (msg_ctxt_id != buf) + free (msg_ctxt_id); +#endif + if (!(translation == msg_ctxt_id || translation == msgid_plural)) + return translation; + } + return (n == 1 ? msgid : msgid_plural); +} + +#endif /* _LIBGETTEXT_H */ diff --git a/src/bin/findutils/gnulib/lib/hash-pjw.c b/src/bin/findutils/gnulib/lib/hash-pjw.c new file mode 100644 index 0000000000..42164f61d5 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/hash-pjw.c @@ -0,0 +1,40 @@ +/* hash-pjw.c -- compute a hash value from a NUL-terminated string. + + Copyright (C) 2001, 2003, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "hash-pjw.h" + +#include + +#define SIZE_BITS (sizeof (size_t) * CHAR_BIT) + +/* A hash function for NUL-terminated char* strings using + the method described by Bruno Haible. + See http://www.haible.de/bruno/hashfunc.html. */ + +size_t +hash_pjw (const void *x, size_t tablesize) +{ + const char *s; + size_t h = 0; + + for (s = x; *s; s++) + h = *s + ((h << 9) | (h >> (SIZE_BITS - 9))); + + return h % tablesize; +} diff --git a/src/bin/findutils/gnulib/lib/hash-pjw.h b/src/bin/findutils/gnulib/lib/hash-pjw.h new file mode 100644 index 0000000000..1fddb202ff --- /dev/null +++ b/src/bin/findutils/gnulib/lib/hash-pjw.h @@ -0,0 +1,23 @@ +/* hash-pjw.h -- declaration for a simple hash function + Copyright (C) 2001, 2003 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +/* Compute a hash code for a NUL-terminated string starting at X, + and return the hash code modulo TABLESIZE. + The result is platform dependent: it depends on the size of the 'size_t' + type and on the signedness of the 'char' type. */ +extern size_t hash_pjw (void const *x, size_t tablesize); diff --git a/src/bin/findutils/gnulib/lib/hash-triple.c b/src/bin/findutils/gnulib/lib/hash-triple.c new file mode 100644 index 0000000000..ef8e13848f --- /dev/null +++ b/src/bin/findutils/gnulib/lib/hash-triple.c @@ -0,0 +1,77 @@ +/* Hash functions for file-related triples: name, device, inode. + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include + +#include "hash-triple.h" + +#include +#include + +#include "hash-pjw.h" +#include "same.h" +#include "same-inode.h" + +#define STREQ(a, b) (strcmp ((a), (b)) == 0) + +/* Hash an F_triple, and *do* consider the file name. */ +size_t +triple_hash (void const *x, size_t table_size) +{ + struct F_triple const *p = x; + size_t tmp = hash_pjw (p->name, table_size); + + /* Ignoring the device number here should be fine. */ + return (tmp ^ p->st_ino) % table_size; +} + +/* Hash an F_triple, without considering the file name. */ +size_t +triple_hash_no_name (void const *x, size_t table_size) +{ + struct F_triple const *p = x; + + /* Ignoring the device number here should be fine. */ + return p->st_ino % table_size; +} + +/* Compare two F_triple structs. */ +bool +triple_compare (void const *x, void const *y) +{ + struct F_triple const *a = x; + struct F_triple const *b = y; + return (SAME_INODE (*a, *b) && same_name (a->name, b->name)) ? true : false; +} + +bool +triple_compare_ino_str (void const *x, void const *y) +{ + struct F_triple const *a = x; + struct F_triple const *b = y; + return (SAME_INODE (*a, *b) && STREQ (a->name, b->name)) ? true : false; +} + +/* Free an F_triple. */ +void +triple_free (void *x) +{ + struct F_triple *a = x; + free (a->name); + free (a); +} diff --git a/src/bin/findutils/gnulib/lib/hash-triple.h b/src/bin/findutils/gnulib/lib/hash-triple.h new file mode 100644 index 0000000000..51863c9dff --- /dev/null +++ b/src/bin/findutils/gnulib/lib/hash-triple.h @@ -0,0 +1,22 @@ +#ifndef HASH_TRIPLE_H +#define HASH_TRIPLE_H + +#include +#include +#include + +/* Describe a just-created or just-renamed destination file. */ +struct F_triple +{ + char *name; + ino_t st_ino; + dev_t st_dev; +}; + +extern size_t triple_hash (void const *x, size_t table_size); +extern size_t triple_hash_no_name (void const *x, size_t table_size); +extern bool triple_compare (void const *x, void const *y); +extern bool triple_compare_ino_str (void const *x, void const *y); +extern void triple_free (void *x); + +#endif diff --git a/src/bin/findutils/gnulib/lib/hash.c b/src/bin/findutils/gnulib/lib/hash.c new file mode 100644 index 0000000000..7d76d45f71 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/hash.c @@ -0,0 +1,1049 @@ +/* hash - hashing table processing. + + Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2006, 2007 Free + Software Foundation, Inc. + + Written by Jim Meyering, 1992. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* A generic hash table package. */ + +/* Define USE_OBSTACK to 1 if you want the allocator to use obstacks instead + of malloc. If you change USE_OBSTACK, you have to recompile! */ + +#include + +#include "hash.h" +#include "xalloc.h" + +#include +#include +#include + +#if USE_OBSTACK +# include "obstack.h" +# ifndef obstack_chunk_alloc +# define obstack_chunk_alloc malloc +# endif +# ifndef obstack_chunk_free +# define obstack_chunk_free free +# endif +#endif + +#ifndef SIZE_MAX +# define SIZE_MAX ((size_t) -1) +#endif + +struct hash_table + { + /* The array of buckets starts at BUCKET and extends to BUCKET_LIMIT-1, + for a possibility of N_BUCKETS. Among those, N_BUCKETS_USED buckets + are not empty, there are N_ENTRIES active entries in the table. */ + struct hash_entry *bucket; + struct hash_entry const *bucket_limit; + size_t n_buckets; + size_t n_buckets_used; + size_t n_entries; + + /* Tuning arguments, kept in a physicaly separate structure. */ + const Hash_tuning *tuning; + + /* Three functions are given to `hash_initialize', see the documentation + block for this function. In a word, HASHER randomizes a user entry + into a number up from 0 up to some maximum minus 1; COMPARATOR returns + true if two user entries compare equally; and DATA_FREER is the cleanup + function for a user entry. */ + Hash_hasher hasher; + Hash_comparator comparator; + Hash_data_freer data_freer; + + /* A linked list of freed struct hash_entry structs. */ + struct hash_entry *free_entry_list; + +#if USE_OBSTACK + /* Whenever obstacks are used, it is possible to allocate all overflowed + entries into a single stack, so they all can be freed in a single + operation. It is not clear if the speedup is worth the trouble. */ + struct obstack entry_stack; +#endif + }; + +/* A hash table contains many internal entries, each holding a pointer to + some user provided data (also called a user entry). An entry indistinctly + refers to both the internal entry and its associated user entry. A user + entry contents may be hashed by a randomization function (the hashing + function, or just `hasher' for short) into a number (or `slot') between 0 + and the current table size. At each slot position in the hash table, + starts a linked chain of entries for which the user data all hash to this + slot. A bucket is the collection of all entries hashing to the same slot. + + A good `hasher' function will distribute entries rather evenly in buckets. + In the ideal case, the length of each bucket is roughly the number of + entries divided by the table size. Finding the slot for a data is usually + done in constant time by the `hasher', and the later finding of a precise + entry is linear in time with the size of the bucket. Consequently, a + larger hash table size (that is, a larger number of buckets) is prone to + yielding shorter chains, *given* the `hasher' function behaves properly. + + Long buckets slow down the lookup algorithm. One might use big hash table + sizes in hope to reduce the average length of buckets, but this might + become inordinate, as unused slots in the hash table take some space. The + best bet is to make sure you are using a good `hasher' function (beware + that those are not that easy to write! :-), and to use a table size + larger than the actual number of entries. */ + +/* If an insertion makes the ratio of nonempty buckets to table size larger + than the growth threshold (a number between 0.0 and 1.0), then increase + the table size by multiplying by the growth factor (a number greater than + 1.0). The growth threshold defaults to 0.8, and the growth factor + defaults to 1.414, meaning that the table will have doubled its size + every second time 80% of the buckets get used. */ +#define DEFAULT_GROWTH_THRESHOLD 0.8 +#define DEFAULT_GROWTH_FACTOR 1.414 + +/* If a deletion empties a bucket and causes the ratio of used buckets to + table size to become smaller than the shrink threshold (a number between + 0.0 and 1.0), then shrink the table by multiplying by the shrink factor (a + number greater than the shrink threshold but smaller than 1.0). The shrink + threshold and factor default to 0.0 and 1.0, meaning that the table never + shrinks. */ +#define DEFAULT_SHRINK_THRESHOLD 0.0 +#define DEFAULT_SHRINK_FACTOR 1.0 + +/* Use this to initialize or reset a TUNING structure to + some sensible values. */ +static const Hash_tuning default_tuning = + { + DEFAULT_SHRINK_THRESHOLD, + DEFAULT_SHRINK_FACTOR, + DEFAULT_GROWTH_THRESHOLD, + DEFAULT_GROWTH_FACTOR, + false + }; + +/* Information and lookup. */ + +/* The following few functions provide information about the overall hash + table organization: the number of entries, number of buckets and maximum + length of buckets. */ + +/* Return the number of buckets in the hash table. The table size, the total + number of buckets (used plus unused), or the maximum number of slots, are + the same quantity. */ + +size_t +hash_get_n_buckets (const Hash_table *table) +{ + return table->n_buckets; +} + +/* Return the number of slots in use (non-empty buckets). */ + +size_t +hash_get_n_buckets_used (const Hash_table *table) +{ + return table->n_buckets_used; +} + +/* Return the number of active entries. */ + +size_t +hash_get_n_entries (const Hash_table *table) +{ + return table->n_entries; +} + +/* Return the length of the longest chain (bucket). */ + +size_t +hash_get_max_bucket_length (const Hash_table *table) +{ + struct hash_entry const *bucket; + size_t max_bucket_length = 0; + + for (bucket = table->bucket; bucket < table->bucket_limit; bucket++) + { + if (bucket->data) + { + struct hash_entry const *cursor = bucket; + size_t bucket_length = 1; + + while (cursor = cursor->next, cursor) + bucket_length++; + + if (bucket_length > max_bucket_length) + max_bucket_length = bucket_length; + } + } + + return max_bucket_length; +} + +/* Do a mild validation of a hash table, by traversing it and checking two + statistics. */ + +bool +hash_table_ok (const Hash_table *table) +{ + struct hash_entry const *bucket; + size_t n_buckets_used = 0; + size_t n_entries = 0; + + for (bucket = table->bucket; bucket < table->bucket_limit; bucket++) + { + if (bucket->data) + { + struct hash_entry const *cursor = bucket; + + /* Count bucket head. */ + n_buckets_used++; + n_entries++; + + /* Count bucket overflow. */ + while (cursor = cursor->next, cursor) + n_entries++; + } + } + + if (n_buckets_used == table->n_buckets_used && n_entries == table->n_entries) + return true; + + return false; +} + +void +hash_print_statistics (const Hash_table *table, FILE *stream) +{ + size_t n_entries = hash_get_n_entries (table); + size_t n_buckets = hash_get_n_buckets (table); + size_t n_buckets_used = hash_get_n_buckets_used (table); + size_t max_bucket_length = hash_get_max_bucket_length (table); + + fprintf (stream, "# entries: %lu\n", (unsigned long int) n_entries); + fprintf (stream, "# buckets: %lu\n", (unsigned long int) n_buckets); + fprintf (stream, "# buckets used: %lu (%.2f%%)\n", + (unsigned long int) n_buckets_used, + (100.0 * n_buckets_used) / n_buckets); + fprintf (stream, "max bucket length: %lu\n", + (unsigned long int) max_bucket_length); +} + +/* If ENTRY matches an entry already in the hash table, return the + entry from the table. Otherwise, return NULL. */ + +void * +hash_lookup (const Hash_table *table, const void *entry) +{ + struct hash_entry const *bucket + = table->bucket + table->hasher (entry, table->n_buckets); + struct hash_entry const *cursor; + + if (! (bucket < table->bucket_limit)) + abort (); + + if (bucket->data == NULL) + return NULL; + + for (cursor = bucket; cursor; cursor = cursor->next) + if (table->comparator (entry, cursor->data)) + return cursor->data; + + return NULL; +} + +/* Walking. */ + +/* The functions in this page traverse the hash table and process the + contained entries. For the traversal to work properly, the hash table + should not be resized nor modified while any particular entry is being + processed. In particular, entries should not be added or removed. */ + +/* Return the first data in the table, or NULL if the table is empty. */ + +void * +hash_get_first (const Hash_table *table) +{ + struct hash_entry const *bucket; + + if (table->n_entries == 0) + return NULL; + + for (bucket = table->bucket; ; bucket++) + if (! (bucket < table->bucket_limit)) + abort (); + else if (bucket->data) + return bucket->data; +} + +/* Return the user data for the entry following ENTRY, where ENTRY has been + returned by a previous call to either `hash_get_first' or `hash_get_next'. + Return NULL if there are no more entries. */ + +void * +hash_get_next (const Hash_table *table, const void *entry) +{ + struct hash_entry const *bucket + = table->bucket + table->hasher (entry, table->n_buckets); + struct hash_entry const *cursor; + + if (! (bucket < table->bucket_limit)) + abort (); + + /* Find next entry in the same bucket. */ + for (cursor = bucket; cursor; cursor = cursor->next) + if (cursor->data == entry && cursor->next) + return cursor->next->data; + + /* Find first entry in any subsequent bucket. */ + while (++bucket < table->bucket_limit) + if (bucket->data) + return bucket->data; + + /* None found. */ + return NULL; +} + +/* Fill BUFFER with pointers to active user entries in the hash table, then + return the number of pointers copied. Do not copy more than BUFFER_SIZE + pointers. */ + +size_t +hash_get_entries (const Hash_table *table, void **buffer, + size_t buffer_size) +{ + size_t counter = 0; + struct hash_entry const *bucket; + struct hash_entry const *cursor; + + for (bucket = table->bucket; bucket < table->bucket_limit; bucket++) + { + if (bucket->data) + { + for (cursor = bucket; cursor; cursor = cursor->next) + { + if (counter >= buffer_size) + return counter; + buffer[counter++] = cursor->data; + } + } + } + + return counter; +} + +/* Call a PROCESSOR function for each entry of a hash table, and return the + number of entries for which the processor function returned success. A + pointer to some PROCESSOR_DATA which will be made available to each call to + the processor function. The PROCESSOR accepts two arguments: the first is + the user entry being walked into, the second is the value of PROCESSOR_DATA + as received. The walking continue for as long as the PROCESSOR function + returns nonzero. When it returns zero, the walking is interrupted. */ + +size_t +hash_do_for_each (const Hash_table *table, Hash_processor processor, + void *processor_data) +{ + size_t counter = 0; + struct hash_entry const *bucket; + struct hash_entry const *cursor; + + for (bucket = table->bucket; bucket < table->bucket_limit; bucket++) + { + if (bucket->data) + { + for (cursor = bucket; cursor; cursor = cursor->next) + { + if (!(*processor) (cursor->data, processor_data)) + return counter; + counter++; + } + } + } + + return counter; +} + +/* Allocation and clean-up. */ + +/* Return a hash index for a NUL-terminated STRING between 0 and N_BUCKETS-1. + This is a convenience routine for constructing other hashing functions. */ + +#if USE_DIFF_HASH + +/* About hashings, Paul Eggert writes to me (FP), on 1994-01-01: "Please see + B. J. McKenzie, R. Harries & T. Bell, Selecting a hashing algorithm, + Software--practice & experience 20, 2 (Feb 1990), 209-224. Good hash + algorithms tend to be domain-specific, so what's good for [diffutils'] io.c + may not be good for your application." */ + +size_t +hash_string (const char *string, size_t n_buckets) +{ +# define ROTATE_LEFT(Value, Shift) \ + ((Value) << (Shift) | (Value) >> ((sizeof (size_t) * CHAR_BIT) - (Shift))) +# define HASH_ONE_CHAR(Value, Byte) \ + ((Byte) + ROTATE_LEFT (Value, 7)) + + size_t value = 0; + unsigned char ch; + + for (; (ch = *string); string++) + value = HASH_ONE_CHAR (value, ch); + return value % n_buckets; + +# undef ROTATE_LEFT +# undef HASH_ONE_CHAR +} + +#else /* not USE_DIFF_HASH */ + +/* This one comes from `recode', and performs a bit better than the above as + per a few experiments. It is inspired from a hashing routine found in the + very old Cyber `snoop', itself written in typical Greg Mansfield style. + (By the way, what happened to this excellent man? Is he still alive?) */ + +size_t +hash_string (const char *string, size_t n_buckets) +{ + size_t value = 0; + unsigned char ch; + + for (; (ch = *string); string++) + value = (value * 31 + ch) % n_buckets; + return value; +} + +#endif /* not USE_DIFF_HASH */ + +/* Return true if CANDIDATE is a prime number. CANDIDATE should be an odd + number at least equal to 11. */ + +static bool +is_prime (size_t candidate) +{ + size_t divisor = 3; + size_t square = divisor * divisor; + + while (square < candidate && (candidate % divisor)) + { + divisor++; + square += 4 * divisor; + divisor++; + } + + return (candidate % divisor ? true : false); +} + +/* Round a given CANDIDATE number up to the nearest prime, and return that + prime. Primes lower than 10 are merely skipped. */ + +static size_t +next_prime (size_t candidate) +{ + /* Skip small primes. */ + if (candidate < 10) + candidate = 10; + + /* Make it definitely odd. */ + candidate |= 1; + + while (!is_prime (candidate)) + candidate += 2; + + return candidate; +} + +void +hash_reset_tuning (Hash_tuning *tuning) +{ + *tuning = default_tuning; +} + +/* For the given hash TABLE, check the user supplied tuning structure for + reasonable values, and return true if there is no gross error with it. + Otherwise, definitively reset the TUNING field to some acceptable default + in the hash table (that is, the user loses the right of further modifying + tuning arguments), and return false. */ + +static bool +check_tuning (Hash_table *table) +{ + const Hash_tuning *tuning = table->tuning; + + /* Be a bit stricter than mathematics would require, so that + rounding errors in size calculations do not cause allocations to + fail to grow or shrink as they should. The smallest allocation + is 11 (due to next_prime's algorithm), so an epsilon of 0.1 + should be good enough. */ + float epsilon = 0.1f; + + if (epsilon < tuning->growth_threshold + && tuning->growth_threshold < 1 - epsilon + && 1 + epsilon < tuning->growth_factor + && 0 <= tuning->shrink_threshold + && tuning->shrink_threshold + epsilon < tuning->shrink_factor + && tuning->shrink_factor <= 1 + && tuning->shrink_threshold + epsilon < tuning->growth_threshold) + return true; + + table->tuning = &default_tuning; + return false; +} + +/* Allocate and return a new hash table, or NULL upon failure. The initial + number of buckets is automatically selected so as to _guarantee_ that you + may insert at least CANDIDATE different user entries before any growth of + the hash table size occurs. So, if have a reasonably tight a-priori upper + bound on the number of entries you intend to insert in the hash table, you + may save some table memory and insertion time, by specifying it here. If + the IS_N_BUCKETS field of the TUNING structure is true, the CANDIDATE + argument has its meaning changed to the wanted number of buckets. + + TUNING points to a structure of user-supplied values, in case some fine + tuning is wanted over the default behavior of the hasher. If TUNING is + NULL, the default tuning parameters are used instead. + + The user-supplied HASHER function should be provided. It accepts two + arguments ENTRY and TABLE_SIZE. It computes, by hashing ENTRY contents, a + slot number for that entry which should be in the range 0..TABLE_SIZE-1. + This slot number is then returned. + + The user-supplied COMPARATOR function should be provided. It accepts two + arguments pointing to user data, it then returns true for a pair of entries + that compare equal, or false otherwise. This function is internally called + on entries which are already known to hash to the same bucket index. + + The user-supplied DATA_FREER function, when not NULL, may be later called + with the user data as an argument, just before the entry containing the + data gets freed. This happens from within `hash_free' or `hash_clear'. + You should specify this function only if you want these functions to free + all of your `data' data. This is typically the case when your data is + simply an auxiliary struct that you have malloc'd to aggregate several + values. */ + +Hash_table * +hash_initialize (size_t candidate, const Hash_tuning *tuning, + Hash_hasher hasher, Hash_comparator comparator, + Hash_data_freer data_freer) +{ + Hash_table *table; + + if (hasher == NULL || comparator == NULL) + return NULL; + + table = malloc (sizeof *table); + if (table == NULL) + return NULL; + + if (!tuning) + tuning = &default_tuning; + table->tuning = tuning; + if (!check_tuning (table)) + { + /* Fail if the tuning options are invalid. This is the only occasion + when the user gets some feedback about it. Once the table is created, + if the user provides invalid tuning options, we silently revert to + using the defaults, and ignore further request to change the tuning + options. */ + goto fail; + } + + if (!tuning->is_n_buckets) + { + float new_candidate = candidate / tuning->growth_threshold; + if (SIZE_MAX <= new_candidate) + goto fail; + candidate = new_candidate; + } + + if (xalloc_oversized (candidate, sizeof *table->bucket)) + goto fail; + table->n_buckets = next_prime (candidate); + if (xalloc_oversized (table->n_buckets, sizeof *table->bucket)) + goto fail; + + table->bucket = calloc (table->n_buckets, sizeof *table->bucket); + if (table->bucket == NULL) + goto fail; + table->bucket_limit = table->bucket + table->n_buckets; + table->n_buckets_used = 0; + table->n_entries = 0; + + table->hasher = hasher; + table->comparator = comparator; + table->data_freer = data_freer; + + table->free_entry_list = NULL; +#if USE_OBSTACK + obstack_init (&table->entry_stack); +#endif + return table; + + fail: + free (table); + return NULL; +} + +/* Make all buckets empty, placing any chained entries on the free list. + Apply the user-specified function data_freer (if any) to the datas of any + affected entries. */ + +void +hash_clear (Hash_table *table) +{ + struct hash_entry *bucket; + + for (bucket = table->bucket; bucket < table->bucket_limit; bucket++) + { + if (bucket->data) + { + struct hash_entry *cursor; + struct hash_entry *next; + + /* Free the bucket overflow. */ + for (cursor = bucket->next; cursor; cursor = next) + { + if (table->data_freer) + (*table->data_freer) (cursor->data); + cursor->data = NULL; + + next = cursor->next; + /* Relinking is done one entry at a time, as it is to be expected + that overflows are either rare or short. */ + cursor->next = table->free_entry_list; + table->free_entry_list = cursor; + } + + /* Free the bucket head. */ + if (table->data_freer) + (*table->data_freer) (bucket->data); + bucket->data = NULL; + bucket->next = NULL; + } + } + + table->n_buckets_used = 0; + table->n_entries = 0; +} + +/* Reclaim all storage associated with a hash table. If a data_freer + function has been supplied by the user when the hash table was created, + this function applies it to the data of each entry before freeing that + entry. */ + +void +hash_free (Hash_table *table) +{ + struct hash_entry *bucket; + struct hash_entry *cursor; + struct hash_entry *next; + + /* Call the user data_freer function. */ + if (table->data_freer && table->n_entries) + { + for (bucket = table->bucket; bucket < table->bucket_limit; bucket++) + { + if (bucket->data) + { + for (cursor = bucket; cursor; cursor = cursor->next) + { + (*table->data_freer) (cursor->data); + } + } + } + } + +#if USE_OBSTACK + + obstack_free (&table->entry_stack, NULL); + +#else + + /* Free all bucket overflowed entries. */ + for (bucket = table->bucket; bucket < table->bucket_limit; bucket++) + { + for (cursor = bucket->next; cursor; cursor = next) + { + next = cursor->next; + free (cursor); + } + } + + /* Also reclaim the internal list of previously freed entries. */ + for (cursor = table->free_entry_list; cursor; cursor = next) + { + next = cursor->next; + free (cursor); + } + +#endif + + /* Free the remainder of the hash table structure. */ + free (table->bucket); + free (table); +} + +/* Insertion and deletion. */ + +/* Get a new hash entry for a bucket overflow, possibly by reclying a + previously freed one. If this is not possible, allocate a new one. */ + +static struct hash_entry * +allocate_entry (Hash_table *table) +{ + struct hash_entry *new; + + if (table->free_entry_list) + { + new = table->free_entry_list; + table->free_entry_list = new->next; + } + else + { +#if USE_OBSTACK + new = obstack_alloc (&table->entry_stack, sizeof *new); +#else + new = malloc (sizeof *new); +#endif + } + + return new; +} + +/* Free a hash entry which was part of some bucket overflow, + saving it for later recycling. */ + +static void +free_entry (Hash_table *table, struct hash_entry *entry) +{ + entry->data = NULL; + entry->next = table->free_entry_list; + table->free_entry_list = entry; +} + +/* This private function is used to help with insertion and deletion. When + ENTRY matches an entry in the table, return a pointer to the corresponding + user data and set *BUCKET_HEAD to the head of the selected bucket. + Otherwise, return NULL. When DELETE is true and ENTRY matches an entry in + the table, unlink the matching entry. */ + +static void * +hash_find_entry (Hash_table *table, const void *entry, + struct hash_entry **bucket_head, bool delete) +{ + struct hash_entry *bucket + = table->bucket + table->hasher (entry, table->n_buckets); + struct hash_entry *cursor; + + if (! (bucket < table->bucket_limit)) + abort (); + + *bucket_head = bucket; + + /* Test for empty bucket. */ + if (bucket->data == NULL) + return NULL; + + /* See if the entry is the first in the bucket. */ + if ((*table->comparator) (entry, bucket->data)) + { + void *data = bucket->data; + + if (delete) + { + if (bucket->next) + { + struct hash_entry *next = bucket->next; + + /* Bump the first overflow entry into the bucket head, then save + the previous first overflow entry for later recycling. */ + *bucket = *next; + free_entry (table, next); + } + else + { + bucket->data = NULL; + } + } + + return data; + } + + /* Scan the bucket overflow. */ + for (cursor = bucket; cursor->next; cursor = cursor->next) + { + if ((*table->comparator) (entry, cursor->next->data)) + { + void *data = cursor->next->data; + + if (delete) + { + struct hash_entry *next = cursor->next; + + /* Unlink the entry to delete, then save the freed entry for later + recycling. */ + cursor->next = next->next; + free_entry (table, next); + } + + return data; + } + } + + /* No entry found. */ + return NULL; +} + +/* For an already existing hash table, change the number of buckets through + specifying CANDIDATE. The contents of the hash table are preserved. The + new number of buckets is automatically selected so as to _guarantee_ that + the table may receive at least CANDIDATE different user entries, including + those already in the table, before any other growth of the hash table size + occurs. If TUNING->IS_N_BUCKETS is true, then CANDIDATE specifies the + exact number of buckets desired. */ + +bool +hash_rehash (Hash_table *table, size_t candidate) +{ + Hash_table *new_table; + struct hash_entry *bucket; + struct hash_entry *cursor; + struct hash_entry *next; + + new_table = hash_initialize (candidate, table->tuning, table->hasher, + table->comparator, table->data_freer); + if (new_table == NULL) + return false; + + /* Merely reuse the extra old space into the new table. */ +#if USE_OBSTACK + obstack_free (&new_table->entry_stack, NULL); + new_table->entry_stack = table->entry_stack; +#endif + new_table->free_entry_list = table->free_entry_list; + + for (bucket = table->bucket; bucket < table->bucket_limit; bucket++) + if (bucket->data) + for (cursor = bucket; cursor; cursor = next) + { + void *data = cursor->data; + struct hash_entry *new_bucket + = (new_table->bucket + + new_table->hasher (data, new_table->n_buckets)); + + if (! (new_bucket < new_table->bucket_limit)) + abort (); + + next = cursor->next; + + if (new_bucket->data) + { + if (cursor == bucket) + { + /* Allocate or recycle an entry, when moving from a bucket + header into a bucket overflow. */ + struct hash_entry *new_entry = allocate_entry (new_table); + + if (new_entry == NULL) + return false; + + new_entry->data = data; + new_entry->next = new_bucket->next; + new_bucket->next = new_entry; + } + else + { + /* Merely relink an existing entry, when moving from a + bucket overflow into a bucket overflow. */ + cursor->next = new_bucket->next; + new_bucket->next = cursor; + } + } + else + { + /* Free an existing entry, when moving from a bucket + overflow into a bucket header. Also take care of the + simple case of moving from a bucket header into a bucket + header. */ + new_bucket->data = data; + new_table->n_buckets_used++; + if (cursor != bucket) + free_entry (new_table, cursor); + } + } + + free (table->bucket); + table->bucket = new_table->bucket; + table->bucket_limit = new_table->bucket_limit; + table->n_buckets = new_table->n_buckets; + table->n_buckets_used = new_table->n_buckets_used; + table->free_entry_list = new_table->free_entry_list; + /* table->n_entries already holds its value. */ +#if USE_OBSTACK + table->entry_stack = new_table->entry_stack; +#endif + free (new_table); + + return true; +} + +/* If ENTRY matches an entry already in the hash table, return the pointer + to the entry from the table. Otherwise, insert ENTRY and return ENTRY. + Return NULL if the storage required for insertion cannot be allocated. */ + +void * +hash_insert (Hash_table *table, const void *entry) +{ + void *data; + struct hash_entry *bucket; + + /* The caller cannot insert a NULL entry. */ + if (! entry) + abort (); + + /* If there's a matching entry already in the table, return that. */ + if ((data = hash_find_entry (table, entry, &bucket, false)) != NULL) + return data; + + /* ENTRY is not matched, it should be inserted. */ + + if (bucket->data) + { + struct hash_entry *new_entry = allocate_entry (table); + + if (new_entry == NULL) + return NULL; + + /* Add ENTRY in the overflow of the bucket. */ + + new_entry->data = (void *) entry; + new_entry->next = bucket->next; + bucket->next = new_entry; + table->n_entries++; + return (void *) entry; + } + + /* Add ENTRY right in the bucket head. */ + + bucket->data = (void *) entry; + table->n_entries++; + table->n_buckets_used++; + + /* If the growth threshold of the buckets in use has been reached, increase + the table size and rehash. There's no point in checking the number of + entries: if the hashing function is ill-conditioned, rehashing is not + likely to improve it. */ + + if (table->n_buckets_used + > table->tuning->growth_threshold * table->n_buckets) + { + /* Check more fully, before starting real work. If tuning arguments + became invalid, the second check will rely on proper defaults. */ + check_tuning (table); + if (table->n_buckets_used + > table->tuning->growth_threshold * table->n_buckets) + { + const Hash_tuning *tuning = table->tuning; + float candidate = + (tuning->is_n_buckets + ? (table->n_buckets * tuning->growth_factor) + : (table->n_buckets * tuning->growth_factor + * tuning->growth_threshold)); + + if (SIZE_MAX <= candidate) + return NULL; + + /* If the rehash fails, arrange to return NULL. */ + if (!hash_rehash (table, candidate)) + entry = NULL; + } + } + + return (void *) entry; +} + +/* If ENTRY is already in the table, remove it and return the just-deleted + data (the user may want to deallocate its storage). If ENTRY is not in the + table, don't modify the table and return NULL. */ + +void * +hash_delete (Hash_table *table, const void *entry) +{ + void *data; + struct hash_entry *bucket; + + data = hash_find_entry (table, entry, &bucket, true); + if (!data) + return NULL; + + table->n_entries--; + if (!bucket->data) + { + table->n_buckets_used--; + + /* If the shrink threshold of the buckets in use has been reached, + rehash into a smaller table. */ + + if (table->n_buckets_used + < table->tuning->shrink_threshold * table->n_buckets) + { + /* Check more fully, before starting real work. If tuning arguments + became invalid, the second check will rely on proper defaults. */ + check_tuning (table); + if (table->n_buckets_used + < table->tuning->shrink_threshold * table->n_buckets) + { + const Hash_tuning *tuning = table->tuning; + size_t candidate = + (tuning->is_n_buckets + ? table->n_buckets * tuning->shrink_factor + : (table->n_buckets * tuning->shrink_factor + * tuning->growth_threshold)); + + hash_rehash (table, candidate); + } + } + } + + return data; +} + +/* Testing. */ + +#if TESTING + +void +hash_print (const Hash_table *table) +{ + struct hash_entry const *bucket; + + for (bucket = table->bucket; bucket < table->bucket_limit; bucket++) + { + struct hash_entry *cursor; + + if (bucket) + printf ("%lu:\n", (unsigned long int) (bucket - table->bucket)); + + for (cursor = bucket; cursor; cursor = cursor->next) + { + char const *s = cursor->data; + /* FIXME */ + if (s) + printf (" %s\n", s); + } + } +} + +#endif /* TESTING */ diff --git a/src/bin/findutils/gnulib/lib/hash.h b/src/bin/findutils/gnulib/lib/hash.h new file mode 100644 index 0000000000..fc1af28a97 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/hash.h @@ -0,0 +1,87 @@ +/* hash - hashing table processing. + Copyright (C) 1998, 1999, 2001, 2003 Free Software Foundation, Inc. + Written by Jim Meyering , 1998. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* A generic hash table package. */ + +/* Make sure USE_OBSTACK is defined to 1 if you want the allocator to use + obstacks instead of malloc, and recompile `hash.c' with same setting. */ + +#ifndef HASH_H_ +# define HASH_H_ + +# include +# include + +typedef size_t (*Hash_hasher) (const void *, size_t); +typedef bool (*Hash_comparator) (const void *, const void *); +typedef void (*Hash_data_freer) (void *); +typedef bool (*Hash_processor) (void *, void *); + +struct hash_entry + { + void *data; + struct hash_entry *next; + }; + +struct hash_tuning + { + /* This structure is mainly used for `hash_initialize', see the block + documentation of `hash_reset_tuning' for more complete comments. */ + + float shrink_threshold; /* ratio of used buckets to trigger a shrink */ + float shrink_factor; /* ratio of new smaller size to original size */ + float growth_threshold; /* ratio of used buckets to trigger a growth */ + float growth_factor; /* ratio of new bigger size to original size */ + bool is_n_buckets; /* if CANDIDATE really means table size */ + }; + +typedef struct hash_tuning Hash_tuning; + +struct hash_table; + +typedef struct hash_table Hash_table; + +/* Information and lookup. */ +size_t hash_get_n_buckets (const Hash_table *); +size_t hash_get_n_buckets_used (const Hash_table *); +size_t hash_get_n_entries (const Hash_table *); +size_t hash_get_max_bucket_length (const Hash_table *); +bool hash_table_ok (const Hash_table *); +void hash_print_statistics (const Hash_table *, FILE *); +void *hash_lookup (const Hash_table *, const void *); + +/* Walking. */ +void *hash_get_first (const Hash_table *); +void *hash_get_next (const Hash_table *, const void *); +size_t hash_get_entries (const Hash_table *, void **, size_t); +size_t hash_do_for_each (const Hash_table *, Hash_processor, void *); + +/* Allocation and clean-up. */ +size_t hash_string (const char *, size_t); +void hash_reset_tuning (Hash_tuning *); +Hash_table *hash_initialize (size_t, const Hash_tuning *, + Hash_hasher, Hash_comparator, + Hash_data_freer); +void hash_clear (Hash_table *); +void hash_free (Hash_table *); + +/* Insertion and deletion. */ +bool hash_rehash (Hash_table *, size_t); +void *hash_insert (Hash_table *, const void *); +void *hash_delete (Hash_table *, const void *); + +#endif diff --git a/src/bin/findutils/gnulib/lib/human.c b/src/bin/findutils/gnulib/lib/human.c new file mode 100644 index 0000000000..c7291b7324 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/human.c @@ -0,0 +1,471 @@ +/* human.c -- print human readable file size + + Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, + 2005, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert and Larry McVoy. */ + +#include + +#include "human.h" + +#include +#include +#include +#include + +#include +#include +#include + +/* The maximum length of a suffix like "KiB". */ +#define HUMAN_READABLE_SUFFIX_LENGTH_MAX 3 + +static const char power_letter[] = +{ + 0, /* not used */ + 'K', /* kibi ('k' for kilo is a special case) */ + 'M', /* mega or mebi */ + 'G', /* giga or gibi */ + 'T', /* tera or tebi */ + 'P', /* peta or pebi */ + 'E', /* exa or exbi */ + 'Z', /* zetta or 2**70 */ + 'Y' /* yotta or 2**80 */ +}; + + +/* If INEXACT_STYLE is not human_round_to_nearest, and if easily + possible, adjust VALUE according to the style. */ + +static long double +adjust_value (int inexact_style, long double value) +{ + /* Do not use the floorl or ceill functions, as that would mean + checking for their presence and possibly linking with the + standard math library, which is a porting pain. So leave the + value alone if it is too large to easily round. */ + if (inexact_style != human_round_to_nearest && value < UINTMAX_MAX) + { + uintmax_t u = value; + value = u + (inexact_style == human_ceiling && u != value); + } + + return value; +} + +/* Group the digits of NUMBER according to the grouping rules of the + current locale. NUMBER contains NUMBERLEN digits. Modify the + bytes pointed to by NUMBER in place, subtracting 1 from NUMBER for + each byte inserted. Return the starting address of the modified + number. + + To group the digits, use GROUPING and THOUSANDS_SEP as in `struct + lconv' from . */ + +static char * +group_number (char *number, size_t numberlen, + char const *grouping, char const *thousands_sep) +{ + register char *d; + size_t grouplen = SIZE_MAX; + size_t thousands_seplen = strlen (thousands_sep); + size_t i = numberlen; + + /* The maximum possible value for NUMBERLEN is the number of digits + in the square of the largest uintmax_t, so double the size needed. */ + char buf[2 * INT_STRLEN_BOUND (uintmax_t) + 1]; + + memcpy (buf, number, numberlen); + d = number + numberlen; + + for (;;) + { + unsigned char g = *grouping; + + if (g) + { + grouplen = g < CHAR_MAX ? g : i; + grouping++; + } + + if (i < grouplen) + grouplen = i; + + d -= grouplen; + i -= grouplen; + memcpy (d, buf + i, grouplen); + if (i == 0) + return d; + + d -= thousands_seplen; + memcpy (d, thousands_sep, thousands_seplen); + } +} + +/* Convert N to a human readable format in BUF, using the options OPTS. + + N is expressed in units of FROM_BLOCK_SIZE. FROM_BLOCK_SIZE must + be nonnegative. + + Use units of TO_BLOCK_SIZE in the output number. TO_BLOCK_SIZE + must be positive. + + Use (OPTS & (human_round_to_nearest | human_floor | human_ceiling)) + to determine whether to take the ceiling or floor of any result + that cannot be expressed exactly. + + If (OPTS & human_group_digits), group the thousands digits + according to the locale, e.g., `1,000,000' in an American English + locale. + + If (OPTS & human_autoscale), deduce the output block size + automatically; TO_BLOCK_SIZE must be 1 but it has no effect on the + output. Use powers of 1024 if (OPTS & human_base_1024), and powers + of 1000 otherwise. For example, assuming powers of 1024, 8500 + would be converted to 8.3, 133456345 to 127, 56990456345 to 53, and + so on. Numbers smaller than the power aren't modified. + human_autoscale is normally used together with human_SI. + + If (OPTS & human_space_before_unit), use a space to separate the + number from any suffix that is appended as described below. + + If (OPTS & human_SI), append an SI prefix indicating which power is + being used. If in addition (OPTS & human_B), append "B" (if base + 1000) or "iB" (if base 1024) to the SI prefix. When ((OPTS & + human_SI) && ! (OPTS & human_autoscale)), TO_BLOCK_SIZE must be a + power of 1024 or of 1000, depending on (OPTS & + human_base_1024). */ + +char * +human_readable (uintmax_t n, char *buf, int opts, + uintmax_t from_block_size, uintmax_t to_block_size) +{ + int inexact_style = + opts & (human_round_to_nearest | human_floor | human_ceiling); + unsigned int base = opts & human_base_1024 ? 1024 : 1000; + uintmax_t amt; + int tenths; + int exponent = -1; + int exponent_max = sizeof power_letter - 1; + char *p; + char *psuffix; + char const *integerlim; + + /* 0 means adjusted N == AMT.TENTHS; + 1 means AMT.TENTHS < adjusted N < AMT.TENTHS + 0.05; + 2 means adjusted N == AMT.TENTHS + 0.05; + 3 means AMT.TENTHS + 0.05 < adjusted N < AMT.TENTHS + 0.1. */ + int rounding; + + char const *decimal_point = "."; + size_t decimal_pointlen = 1; + char const *grouping = ""; + char const *thousands_sep = ""; + struct lconv const *l = localeconv (); + size_t pointlen = strlen (l->decimal_point); + if (0 < pointlen && pointlen <= MB_LEN_MAX) + { + decimal_point = l->decimal_point; + decimal_pointlen = pointlen; + } + grouping = l->grouping; + if (strlen (l->thousands_sep) <= MB_LEN_MAX) + thousands_sep = l->thousands_sep; + + psuffix = buf + LONGEST_HUMAN_READABLE - HUMAN_READABLE_SUFFIX_LENGTH_MAX; + p = psuffix; + + /* Adjust AMT out of FROM_BLOCK_SIZE units and into TO_BLOCK_SIZE + units. If this can be done exactly with integer arithmetic, do + not use floating point operations. */ + if (to_block_size <= from_block_size) + { + if (from_block_size % to_block_size == 0) + { + uintmax_t multiplier = from_block_size / to_block_size; + amt = n * multiplier; + if (amt / multiplier == n) + { + tenths = 0; + rounding = 0; + goto use_integer_arithmetic; + } + } + } + else if (from_block_size != 0 && to_block_size % from_block_size == 0) + { + uintmax_t divisor = to_block_size / from_block_size; + uintmax_t r10 = (n % divisor) * 10; + uintmax_t r2 = (r10 % divisor) * 2; + amt = n / divisor; + tenths = r10 / divisor; + rounding = r2 < divisor ? 0 < r2 : 2 + (divisor < r2); + goto use_integer_arithmetic; + } + + { + /* Either the result cannot be computed easily using uintmax_t, + or from_block_size is zero. Fall back on floating point. + FIXME: This can yield answers that are slightly off. */ + + long double dto_block_size = to_block_size; + long double damt = n * (from_block_size / dto_block_size); + size_t buflen; + size_t nonintegerlen; + + if (! (opts & human_autoscale)) + { + sprintf (buf, "%.0Lf", adjust_value (inexact_style, damt)); + buflen = strlen (buf); + nonintegerlen = 0; + } + else + { + long double e = 1; + exponent = 0; + + do + { + e *= base; + exponent++; + } + while (e * base <= damt && exponent < exponent_max); + + damt /= e; + + sprintf (buf, "%.1Lf", adjust_value (inexact_style, damt)); + buflen = strlen (buf); + nonintegerlen = decimal_pointlen + 1; + + if (1 + nonintegerlen + ! (opts & human_base_1024) < buflen + || ((opts & human_suppress_point_zero) + && buf[buflen - 1] == '0')) + { + sprintf (buf, "%.0Lf", + adjust_value (inexact_style, damt * 10) / 10); + buflen = strlen (buf); + nonintegerlen = 0; + } + } + + p = psuffix - buflen; + memmove (p, buf, buflen); + integerlim = p + buflen - nonintegerlen; + } + goto do_grouping; + + use_integer_arithmetic: + { + /* The computation can be done exactly, with integer arithmetic. + + Use power of BASE notation if requested and if adjusted AMT is + large enough. */ + + if (opts & human_autoscale) + { + exponent = 0; + + if (base <= amt) + { + do + { + unsigned int r10 = (amt % base) * 10 + tenths; + unsigned int r2 = (r10 % base) * 2 + (rounding >> 1); + amt /= base; + tenths = r10 / base; + rounding = (r2 < base + ? (r2 + rounding) != 0 + : 2 + (base < r2 + rounding)); + exponent++; + } + while (base <= amt && exponent < exponent_max); + + if (amt < 10) + { + if (inexact_style == human_round_to_nearest + ? 2 < rounding + (tenths & 1) + : inexact_style == human_ceiling && 0 < rounding) + { + tenths++; + rounding = 0; + + if (tenths == 10) + { + amt++; + tenths = 0; + } + } + + if (amt < 10 + && (tenths || ! (opts & human_suppress_point_zero))) + { + *--p = '0' + tenths; + p -= decimal_pointlen; + memcpy (p, decimal_point, decimal_pointlen); + tenths = rounding = 0; + } + } + } + } + + if (inexact_style == human_round_to_nearest + ? 5 < tenths + (0 < rounding + (amt & 1)) + : inexact_style == human_ceiling && 0 < tenths + rounding) + { + amt++; + + if ((opts & human_autoscale) + && amt == base && exponent < exponent_max) + { + exponent++; + if (! (opts & human_suppress_point_zero)) + { + *--p = '0'; + p -= decimal_pointlen; + memcpy (p, decimal_point, decimal_pointlen); + } + amt = 1; + } + } + + integerlim = p; + + do + { + int digit = amt % 10; + *--p = digit + '0'; + } + while ((amt /= 10) != 0); + } + + do_grouping: + if (opts & human_group_digits) + p = group_number (p, integerlim - p, grouping, thousands_sep); + + if (opts & human_SI) + { + if (exponent < 0) + { + uintmax_t power; + exponent = 0; + for (power = 1; power < to_block_size; power *= base) + if (++exponent == exponent_max) + break; + } + + if ((exponent | (opts & human_B)) && (opts & human_space_before_unit)) + *psuffix++ = ' '; + + if (exponent) + *psuffix++ = (! (opts & human_base_1024) && exponent == 1 + ? 'k' + : power_letter[exponent]); + + if (opts & human_B) + { + if ((opts & human_base_1024) && exponent) + *psuffix++ = 'i'; + *psuffix++ = 'B'; + } + } + + *psuffix = '\0'; + + return p; +} + + +/* The default block size used for output. This number may change in + the future as disks get larger. */ +#ifndef DEFAULT_BLOCK_SIZE +# define DEFAULT_BLOCK_SIZE 1024 +#endif + +static char const *const block_size_args[] = { "human-readable", "si", 0 }; +static int const block_size_opts[] = + { + human_autoscale + human_SI + human_base_1024, + human_autoscale + human_SI + }; + +static uintmax_t +default_block_size (void) +{ + return getenv ("POSIXLY_CORRECT") ? 512 : DEFAULT_BLOCK_SIZE; +} + +static strtol_error +humblock (char const *spec, uintmax_t *block_size, int *options) +{ + int i; + int opts = 0; + + if (! spec + && ! (spec = getenv ("BLOCK_SIZE")) + && ! (spec = getenv ("BLOCKSIZE"))) + *block_size = default_block_size (); + else + { + if (*spec == '\'') + { + opts |= human_group_digits; + spec++; + } + + if (0 <= (i = ARGMATCH (spec, block_size_args, block_size_opts))) + { + opts |= block_size_opts[i]; + *block_size = 1; + } + else + { + char *ptr; + strtol_error e = xstrtoumax (spec, &ptr, 0, block_size, + "eEgGkKmMpPtTyYzZ0"); + if (e != LONGINT_OK) + { + *options = 0; + return e; + } + for (; ! ('0' <= *spec && *spec <= '9'); spec++) + if (spec == ptr) + { + opts |= human_SI; + if (ptr[-1] == 'B') + opts |= human_B; + if (ptr[-1] != 'B' || ptr[-2] == 'i') + opts |= human_base_1024; + break; + } + } + } + + *options = opts; + return LONGINT_OK; +} + +enum strtol_error +human_options (char const *spec, int *opts, uintmax_t *block_size) +{ + strtol_error e = humblock (spec, block_size, opts); + if (*block_size == 0) + { + *block_size = default_block_size (); + e = LONGINT_INVALID; + } + return e; +} diff --git a/src/bin/findutils/gnulib/lib/human.h b/src/bin/findutils/gnulib/lib/human.h new file mode 100644 index 0000000000..11b1e0cee4 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/human.h @@ -0,0 +1,84 @@ +/* human.h -- print human readable file size + + Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, + 2005, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert and Larry McVoy. */ + +#ifndef HUMAN_H_ +# define HUMAN_H_ 1 + +# include +# include +# include +# include + +# include + +/* A conservative bound on the maximum length of a human-readable string. + The output can be the square of the largest uintmax_t, so double + its size before converting to a bound. + log10 (2.0) < 146/485. Add 1 for integer division truncation. + Also, the output can have a thousands separator between every digit, + so multiply by MB_LEN_MAX + 1 and then subtract MB_LEN_MAX. + Append 1 for a space before the suffix. + Finally, append 3, the maximum length of a suffix. */ +# define LONGEST_HUMAN_READABLE \ + ((2 * sizeof (uintmax_t) * CHAR_BIT * 146 / 485 + 1) * (MB_LEN_MAX + 1) \ + - MB_LEN_MAX + 1 + 3) + +/* Options for human_readable. */ +enum +{ + /* Unless otherwise specified these options may be ORed together. */ + + /* The following three options are mutually exclusive. */ + /* Round to plus infinity (default). */ + human_ceiling = 0, + /* Round to nearest, ties to even. */ + human_round_to_nearest = 1, + /* Round to minus infinity. */ + human_floor = 2, + + /* Group digits together, e.g. `1,000,000'. This uses the + locale-defined grouping; the traditional C locale does not group, + so this has effect only if some other locale is in use. */ + human_group_digits = 4, + + /* When autoscaling, suppress ".0" at end. */ + human_suppress_point_zero = 8, + + /* Scale output and use SI-style units, ignoring the output block size. */ + human_autoscale = 16, + + /* Prefer base 1024 to base 1000. */ + human_base_1024 = 32, + + /* Prepend " " before unit symbol. */ + human_space_before_unit = 64, + + /* Append SI prefix, e.g. "k" or "M". */ + human_SI = 128, + + /* Append "B" (if base 1000) or "iB" (if base 1024) to SI prefix. */ + human_B = 256 +}; + +char *human_readable (uintmax_t, char *, int, uintmax_t, uintmax_t); + +enum strtol_error human_options (char const *, int *, uintmax_t *); + +#endif /* HUMAN_H_ */ diff --git a/src/bin/findutils/gnulib/lib/idcache.c b/src/bin/findutils/gnulib/lib/idcache.c new file mode 100644 index 0000000000..4951873d1d --- /dev/null +++ b/src/bin/findutils/gnulib/lib/idcache.c @@ -0,0 +1,227 @@ +/* idcache.c -- map user and group IDs, cached for speed + + Copyright (C) 1985, 1988, 1989, 1990, 1997, 1998, 2003, 2005-2007 + Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "idcache.h" +#include +#include +#include +#include +#include + +#include + +#include "xalloc.h" + +#ifdef __DJGPP__ +static char digits[] = "0123456789"; +#endif + +struct userid +{ + union + { + uid_t u; + gid_t g; + } id; + struct userid *next; + char name[FLEXIBLE_ARRAY_MEMBER]; +}; + +/* FIXME: provide a function to free any malloc'd storage and reset lists, + so that an application can use code like this just before exiting: + #ifdef lint + idcache_clear (); + #endif +*/ + +static struct userid *user_alist; + +/* Each entry on list is a user name for which the first lookup failed. */ +static struct userid *nouser_alist; + +/* Use the same struct as for userids. */ +static struct userid *group_alist; + +/* Each entry on list is a group name for which the first lookup failed. */ +static struct userid *nogroup_alist; + +/* Translate UID to a login name, with cache, or NULL if unresolved. */ + +char * +getuser (uid_t uid) +{ + struct userid *tail; + struct userid *match = NULL; + + for (tail = user_alist; tail; tail = tail->next) + { + if (tail->id.u == uid) + { + match = tail; + break; + } + } + + if (match == NULL) + { + struct passwd *pwent = getpwuid (uid); + char const *name = pwent ? pwent->pw_name : ""; + match = xmalloc (offsetof (struct userid, name) + strlen (name) + 1); + match->id.u = uid; + strcpy (match->name, name); + + /* Add to the head of the list, so most recently used is first. */ + match->next = user_alist; + user_alist = match; + } + + return match->name[0] ? match->name : NULL; +} + +/* Translate USER to a UID, with cache. + Return NULL if there is no such user. + (We also cache which user names have no passwd entry, + so we don't keep looking them up.) */ + +uid_t * +getuidbyname (const char *user) +{ + struct userid *tail; + struct passwd *pwent; + + for (tail = user_alist; tail; tail = tail->next) + /* Avoid a function call for the most common case. */ + if (*tail->name == *user && !strcmp (tail->name, user)) + return &tail->id.u; + + for (tail = nouser_alist; tail; tail = tail->next) + /* Avoid a function call for the most common case. */ + if (*tail->name == *user && !strcmp (tail->name, user)) + return NULL; + + pwent = getpwnam (user); +#ifdef __DJGPP__ + /* We need to pretend to be the user USER, to make + pwd functions know about an arbitrary user name. */ + if (!pwent && strspn (user, digits) < strlen (user)) + { + setenv ("USER", user, 1); + pwent = getpwnam (user); /* now it will succeed */ + } +#endif + + tail = xmalloc (offsetof (struct userid, name) + strlen (user) + 1); + strcpy (tail->name, user); + + /* Add to the head of the list, so most recently used is first. */ + if (pwent) + { + tail->id.u = pwent->pw_uid; + tail->next = user_alist; + user_alist = tail; + return &tail->id.u; + } + + tail->next = nouser_alist; + nouser_alist = tail; + return NULL; +} + +/* Translate GID to a group name, with cache, or NULL if unresolved. */ + +char * +getgroup (gid_t gid) +{ + struct userid *tail; + struct userid *match = NULL; + + for (tail = group_alist; tail; tail = tail->next) + { + if (tail->id.g == gid) + { + match = tail; + break; + } + } + + if (match == NULL) + { + struct group *grent = getgrgid (gid); + char const *name = grent ? grent->gr_name : ""; + match = xmalloc (offsetof (struct userid, name) + strlen (name) + 1); + match->id.g = gid; + strcpy (match->name, name); + + /* Add to the head of the list, so most recently used is first. */ + match->next = group_alist; + group_alist = match; + } + + return match->name[0] ? match->name : NULL; +} + +/* Translate GROUP to a GID, with cache. + Return NULL if there is no such group. + (We also cache which group names have no group entry, + so we don't keep looking them up.) */ + +gid_t * +getgidbyname (const char *group) +{ + struct userid *tail; + struct group *grent; + + for (tail = group_alist; tail; tail = tail->next) + /* Avoid a function call for the most common case. */ + if (*tail->name == *group && !strcmp (tail->name, group)) + return &tail->id.g; + + for (tail = nogroup_alist; tail; tail = tail->next) + /* Avoid a function call for the most common case. */ + if (*tail->name == *group && !strcmp (tail->name, group)) + return NULL; + + grent = getgrnam (group); +#ifdef __DJGPP__ + /* We need to pretend to belong to group GROUP, to make + grp functions know about an arbitrary group name. */ + if (!grent && strspn (group, digits) < strlen (group)) + { + setenv ("GROUP", group, 1); + grent = getgrnam (group); /* now it will succeed */ + } +#endif + + tail = xmalloc (offsetof (struct userid, name) + strlen (group) + 1); + strcpy (tail->name, group); + + /* Add to the head of the list, so most recently used is first. */ + if (grent) + { + tail->id.g = grent->gr_gid; + tail->next = group_alist; + group_alist = tail; + return &tail->id.g; + } + + tail->next = nogroup_alist; + nogroup_alist = tail; + return NULL; +} diff --git a/src/bin/findutils/gnulib/lib/idcache.h b/src/bin/findutils/gnulib/lib/idcache.h new file mode 100644 index 0000000000..e7573b83f7 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/idcache.h @@ -0,0 +1,11 @@ +#ifndef IDCACHE_H +# define IDCACHE_H 1 + +# include + +extern char *getuser (uid_t uid); +extern char *getgroup (gid_t gid); +extern uid_t *getuidbyname (const char *user); +extern gid_t *getgidbyname (const char *group); + +#endif diff --git a/src/bin/findutils/gnulib/lib/intprops.h b/src/bin/findutils/gnulib/lib/intprops.h new file mode 100644 index 0000000000..002161ee57 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/intprops.h @@ -0,0 +1,77 @@ +/* intprops.h -- properties of integer types + + Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert. */ + +#include + +/* The extra casts in the following macros work around compiler bugs, + e.g., in Cray C 5.0.3.0. */ + +/* True if the arithmetic type T is an integer type. bool counts as + an integer. */ +#define TYPE_IS_INTEGER(t) ((t) 1.5 == 1) + +/* True if negative values of the signed integer type T use two's + complement, ones' complement, or signed magnitude representation, + respectively. Much GNU code assumes two's complement, but some + people like to be portable to all possible C hosts. */ +#define TYPE_TWOS_COMPLEMENT(t) ((t) ~ (t) 0 == (t) -1) +#define TYPE_ONES_COMPLEMENT(t) ((t) ~ (t) 0 == 0) +#define TYPE_SIGNED_MAGNITUDE(t) ((t) ~ (t) 0 < (t) -1) + +/* True if the arithmetic type T is signed. */ +#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1)) + +/* The maximum and minimum values for the integer type T. These + macros have undefined behavior if T is signed and has padding bits. + If this is a problem for you, please let us know how to fix it for + your host. */ +#define TYPE_MINIMUM(t) \ + ((t) (! TYPE_SIGNED (t) \ + ? (t) 0 \ + : TYPE_SIGNED_MAGNITUDE (t) \ + ? ~ (t) 0 \ + : ~ (t) 0 << (sizeof (t) * CHAR_BIT - 1))) +#define TYPE_MAXIMUM(t) \ + ((t) (! TYPE_SIGNED (t) \ + ? (t) -1 \ + : ~ (~ (t) 0 << (sizeof (t) * CHAR_BIT - 1)))) + +/* Return zero if T can be determined to be an unsigned type. + Otherwise, return 1. + When compiling with GCC, INT_STRLEN_BOUND uses this macro to obtain a + tighter bound. Otherwise, it overestimates the true bound by one byte + when applied to unsigned types of size 2, 4, 16, ... bytes. + The symbol signed_type_or_expr__ is private to this header file. */ +#if __GNUC__ >= 2 +# define signed_type_or_expr__(t) TYPE_SIGNED (__typeof__ (t)) +#else +# define signed_type_or_expr__(t) 1 +#endif + +/* Bound on length of the string representing an integer type or expression T. + Subtract 1 for the sign bit if T is signed; log10 (2.0) < 146/485; + add 1 for integer division truncation; add 1 more for a minus sign + if needed. */ +#define INT_STRLEN_BOUND(t) \ + ((sizeof (t) * CHAR_BIT - signed_type_or_expr__ (t)) * 146 / 485 \ + + signed_type_or_expr__ (t) + 1) + +/* Bound on buffer size needed to represent an integer type or expression T, + including the terminating null. */ +#define INT_BUFSIZE_BOUND(t) (INT_STRLEN_BOUND (t) + 1) diff --git a/src/bin/findutils/gnulib/lib/inttypes.h b/src/bin/findutils/gnulib/lib/inttypes.h new file mode 100644 index 0000000000..0b072c6e6d --- /dev/null +++ b/src/bin/findutils/gnulib/lib/inttypes.h @@ -0,0 +1,1124 @@ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +/* Copyright (C) 2006-2007 Free Software Foundation, Inc. + Written by Paul Eggert, Bruno Haible, Derek Price. + This file is part of gnulib. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* + * ISO C 99 for platforms that lack it. + * + */ + +/* Include the original if it exists, and if this file + has not been included yet or if this file includes gnulib stdint.h + which in turn includes this file. + The include_next requires a split double-inclusion guard. */ +#if ! defined INTTYPES_H || defined _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H +# if 1 +# include_next +# endif +#endif + +#if ! defined INTTYPES_H && ! defined _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H +#define INTTYPES_H + +/* Include or the gnulib replacement. */ +#include +/* Get CHAR_BIT. */ +#include + +#if !(INT_MIN == INT32_MIN && INT_MAX == INT32_MAX) +# error "This file assumes that 'int' has exactly 32 bits. Please report your platform and compiler to ." +#endif + +/* The definition of GL_LINK_WARNING is copied here. */ +/* GL_LINK_WARNING("literal string") arranges to emit the literal string as + a linker warning on most glibc systems. + We use a linker warning rather than a preprocessor warning, because + #warning cannot be used inside macros. */ +#ifndef GL_LINK_WARNING + /* This works on platforms with GNU ld and ELF object format. + Testing __GLIBC__ is sufficient for asserting that GNU ld is in use. + Testing __ELF__ guarantees the ELF object format. + Testing __GNUC__ is necessary for the compound expression syntax. */ +# if defined __GLIBC__ && defined __ELF__ && defined __GNUC__ +# define GL_LINK_WARNING(message) \ + GL_LINK_WARNING1 (__FILE__, __LINE__, message) +# define GL_LINK_WARNING1(file, line, message) \ + GL_LINK_WARNING2 (file, line, message) /* macroexpand file and line */ +# define GL_LINK_WARNING2(file, line, message) \ + GL_LINK_WARNING3 (file ":" #line ": warning: " message) +# define GL_LINK_WARNING3(message) \ + ({ static const char warning[sizeof (message)] \ + __attribute__ ((__unused__, \ + __section__ (".gnu.warning"), \ + __aligned__ (1))) \ + = message "\n"; \ + (void)0; \ + }) +# else +# define GL_LINK_WARNING(message) ((void) 0) +# endif +#endif + +/* 7.8.1 Macros for format specifiers */ + +#if ! defined __cplusplus || defined __STDC_FORMAT_MACROS + +# if defined _TNS_R_TARGET + /* Tandem NonStop R series and compatible platforms released before + July 2005 support %Ld but not %lld. */ +# define _LONG_LONG_FORMAT_PREFIX "L" +# else +# define _LONG_LONG_FORMAT_PREFIX "ll" +# endif + +# if !defined PRId8 || 0 +# undef PRId8 +# ifdef INT8_MAX +# define PRId8 "d" +# endif +# endif +# if !defined PRIi8 || 0 +# undef PRIi8 +# ifdef INT8_MAX +# define PRIi8 "i" +# endif +# endif +# if !defined PRIo8 || 0 +# undef PRIo8 +# ifdef UINT8_MAX +# define PRIo8 "o" +# endif +# endif +# if !defined PRIu8 || 0 +# undef PRIu8 +# ifdef UINT8_MAX +# define PRIu8 "u" +# endif +# endif +# if !defined PRIx8 || 0 +# undef PRIx8 +# ifdef UINT8_MAX +# define PRIx8 "x" +# endif +# endif +# if !defined PRIX8 || 0 +# undef PRIX8 +# ifdef UINT8_MAX +# define PRIX8 "X" +# endif +# endif +# if !defined PRId16 || 0 +# undef PRId16 +# ifdef INT16_MAX +# define PRId16 "d" +# endif +# endif +# if !defined PRIi16 || 0 +# undef PRIi16 +# ifdef INT16_MAX +# define PRIi16 "i" +# endif +# endif +# if !defined PRIo16 || 0 +# undef PRIo16 +# ifdef UINT16_MAX +# define PRIo16 "o" +# endif +# endif +# if !defined PRIu16 || 0 +# undef PRIu16 +# ifdef UINT16_MAX +# define PRIu16 "u" +# endif +# endif +# if !defined PRIx16 || 0 +# undef PRIx16 +# ifdef UINT16_MAX +# define PRIx16 "x" +# endif +# endif +# if !defined PRIX16 || 0 +# undef PRIX16 +# ifdef UINT16_MAX +# define PRIX16 "X" +# endif +# endif +# if !defined PRId32 || 0 +# undef PRId32 +# ifdef INT32_MAX +# define PRId32 "d" +# endif +# endif +# if !defined PRIi32 || 0 +# undef PRIi32 +# ifdef INT32_MAX +# define PRIi32 "i" +# endif +# endif +# if !defined PRIo32 || 0 +# undef PRIo32 +# ifdef UINT32_MAX +# define PRIo32 "o" +# endif +# endif +# if !defined PRIu32 || 0 +# undef PRIu32 +# ifdef UINT32_MAX +# define PRIu32 "u" +# endif +# endif +# if !defined PRIx32 || 0 +# undef PRIx32 +# ifdef UINT32_MAX +# define PRIx32 "x" +# endif +# endif +# if !defined PRIX32 || 0 +# undef PRIX32 +# ifdef UINT32_MAX +# define PRIX32 "X" +# endif +# endif +# ifdef INT64_MAX +# if 0 +# define _PRI64_PREFIX "l" +# elif defined _MSC_VER || defined __MINGW32__ +# define _PRI64_PREFIX "I64" +# elif 1 && LONG_MAX >> 30 == 1 +# define _PRI64_PREFIX _LONG_LONG_FORMAT_PREFIX +# endif +# if !defined PRId64 || 0 +# undef PRId64 +# define PRId64 _PRI64_PREFIX "d" +# endif +# if !defined PRIi64 || 0 +# undef PRIi64 +# define PRIi64 _PRI64_PREFIX "i" +# endif +# endif +# ifdef UINT64_MAX +# if 0 +# define _PRIu64_PREFIX "l" +# elif defined _MSC_VER || defined __MINGW32__ +# define _PRIu64_PREFIX "I64" +# elif 1 && ULONG_MAX >> 31 == 1 +# define _PRIu64_PREFIX _LONG_LONG_FORMAT_PREFIX +# endif +# if !defined PRIo64 || 0 +# undef PRIo64 +# define PRIo64 _PRIu64_PREFIX "o" +# endif +# if !defined PRIu64 || 0 +# undef PRIu64 +# define PRIu64 _PRIu64_PREFIX "u" +# endif +# if !defined PRIx64 || 0 +# undef PRIx64 +# define PRIx64 _PRIu64_PREFIX "x" +# endif +# if !defined PRIX64 || 0 +# undef PRIX64 +# define PRIX64 _PRIu64_PREFIX "X" +# endif +# endif + +# if !defined PRIdLEAST8 || 0 +# undef PRIdLEAST8 +# define PRIdLEAST8 "d" +# endif +# if !defined PRIiLEAST8 || 0 +# undef PRIiLEAST8 +# define PRIiLEAST8 "i" +# endif +# if !defined PRIoLEAST8 || 0 +# undef PRIoLEAST8 +# define PRIoLEAST8 "o" +# endif +# if !defined PRIuLEAST8 || 0 +# undef PRIuLEAST8 +# define PRIuLEAST8 "u" +# endif +# if !defined PRIxLEAST8 || 0 +# undef PRIxLEAST8 +# define PRIxLEAST8 "x" +# endif +# if !defined PRIXLEAST8 || 0 +# undef PRIXLEAST8 +# define PRIXLEAST8 "X" +# endif +# if !defined PRIdLEAST16 || 0 +# undef PRIdLEAST16 +# define PRIdLEAST16 "d" +# endif +# if !defined PRIiLEAST16 || 0 +# undef PRIiLEAST16 +# define PRIiLEAST16 "i" +# endif +# if !defined PRIoLEAST16 || 0 +# undef PRIoLEAST16 +# define PRIoLEAST16 "o" +# endif +# if !defined PRIuLEAST16 || 0 +# undef PRIuLEAST16 +# define PRIuLEAST16 "u" +# endif +# if !defined PRIxLEAST16 || 0 +# undef PRIxLEAST16 +# define PRIxLEAST16 "x" +# endif +# if !defined PRIXLEAST16 || 0 +# undef PRIXLEAST16 +# define PRIXLEAST16 "X" +# endif +# if !defined PRIdLEAST32 || 0 +# undef PRIdLEAST32 +# define PRIdLEAST32 "d" +# endif +# if !defined PRIiLEAST32 || 0 +# undef PRIiLEAST32 +# define PRIiLEAST32 "i" +# endif +# if !defined PRIoLEAST32 || 0 +# undef PRIoLEAST32 +# define PRIoLEAST32 "o" +# endif +# if !defined PRIuLEAST32 || 0 +# undef PRIuLEAST32 +# define PRIuLEAST32 "u" +# endif +# if !defined PRIxLEAST32 || 0 +# undef PRIxLEAST32 +# define PRIxLEAST32 "x" +# endif +# if !defined PRIXLEAST32 || 0 +# undef PRIXLEAST32 +# define PRIXLEAST32 "X" +# endif +# ifdef INT64_MAX +# if !defined PRIdLEAST64 || 0 +# undef PRIdLEAST64 +# define PRIdLEAST64 PRId64 +# endif +# if !defined PRIiLEAST64 || 0 +# undef PRIiLEAST64 +# define PRIiLEAST64 PRIi64 +# endif +# endif +# ifdef UINT64_MAX +# if !defined PRIoLEAST64 || 0 +# undef PRIoLEAST64 +# define PRIoLEAST64 PRIo64 +# endif +# if !defined PRIuLEAST64 || 0 +# undef PRIuLEAST64 +# define PRIuLEAST64 PRIu64 +# endif +# if !defined PRIxLEAST64 || 0 +# undef PRIxLEAST64 +# define PRIxLEAST64 PRIx64 +# endif +# if !defined PRIXLEAST64 || 0 +# undef PRIXLEAST64 +# define PRIXLEAST64 PRIX64 +# endif +# endif + +# if !defined PRIdFAST8 || 0 +# undef PRIdFAST8 +# if INT_FAST8_MAX > INT32_MAX +# define PRIdFAST8 PRId64 +# else +# define PRIdFAST8 "d" +# endif +# endif +# if !defined PRIiFAST8 || 0 +# undef PRIiFAST8 +# if INT_FAST8_MAX > INT32_MAX +# define PRIiFAST8 PRIi64 +# else +# define PRIiFAST8 "i" +# endif +# endif +# if !defined PRIoFAST8 || 0 +# undef PRIoFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define PRIoFAST8 PRIo64 +# else +# define PRIoFAST8 "o" +# endif +# endif +# if !defined PRIuFAST8 || 0 +# undef PRIuFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define PRIuFAST8 PRIu64 +# else +# define PRIuFAST8 "u" +# endif +# endif +# if !defined PRIxFAST8 || 0 +# undef PRIxFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define PRIxFAST8 PRIx64 +# else +# define PRIxFAST8 "x" +# endif +# endif +# if !defined PRIXFAST8 || 0 +# undef PRIXFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define PRIXFAST8 PRIX64 +# else +# define PRIXFAST8 "X" +# endif +# endif +# if !defined PRIdFAST16 || 0 +# undef PRIdFAST16 +# if INT_FAST16_MAX > INT32_MAX +# define PRIdFAST16 PRId64 +# else +# define PRIdFAST16 "d" +# endif +# endif +# if !defined PRIiFAST16 || 0 +# undef PRIiFAST16 +# if INT_FAST16_MAX > INT32_MAX +# define PRIiFAST16 PRIi64 +# else +# define PRIiFAST16 "i" +# endif +# endif +# if !defined PRIoFAST16 || 0 +# undef PRIoFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define PRIoFAST16 PRIo64 +# else +# define PRIoFAST16 "o" +# endif +# endif +# if !defined PRIuFAST16 || 0 +# undef PRIuFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define PRIuFAST16 PRIu64 +# else +# define PRIuFAST16 "u" +# endif +# endif +# if !defined PRIxFAST16 || 0 +# undef PRIxFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define PRIxFAST16 PRIx64 +# else +# define PRIxFAST16 "x" +# endif +# endif +# if !defined PRIXFAST16 || 0 +# undef PRIXFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define PRIXFAST16 PRIX64 +# else +# define PRIXFAST16 "X" +# endif +# endif +# if !defined PRIdFAST32 || 0 +# undef PRIdFAST32 +# if INT_FAST32_MAX > INT32_MAX +# define PRIdFAST32 PRId64 +# else +# define PRIdFAST32 "d" +# endif +# endif +# if !defined PRIiFAST32 || 0 +# undef PRIiFAST32 +# if INT_FAST32_MAX > INT32_MAX +# define PRIiFAST32 PRIi64 +# else +# define PRIiFAST32 "i" +# endif +# endif +# if !defined PRIoFAST32 || 0 +# undef PRIoFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define PRIoFAST32 PRIo64 +# else +# define PRIoFAST32 "o" +# endif +# endif +# if !defined PRIuFAST32 || 0 +# undef PRIuFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define PRIuFAST32 PRIu64 +# else +# define PRIuFAST32 "u" +# endif +# endif +# if !defined PRIxFAST32 || 0 +# undef PRIxFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define PRIxFAST32 PRIx64 +# else +# define PRIxFAST32 "x" +# endif +# endif +# if !defined PRIXFAST32 || 0 +# undef PRIXFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define PRIXFAST32 PRIX64 +# else +# define PRIXFAST32 "X" +# endif +# endif +# ifdef INT64_MAX +# if !defined PRIdFAST64 || 0 +# undef PRIdFAST64 +# define PRIdFAST64 PRId64 +# endif +# if !defined PRIiFAST64 || 0 +# undef PRIiFAST64 +# define PRIiFAST64 PRIi64 +# endif +# endif +# ifdef UINT64_MAX +# if !defined PRIoFAST64 || 0 +# undef PRIoFAST64 +# define PRIoFAST64 PRIo64 +# endif +# if !defined PRIuFAST64 || 0 +# undef PRIuFAST64 +# define PRIuFAST64 PRIu64 +# endif +# if !defined PRIxFAST64 || 0 +# undef PRIxFAST64 +# define PRIxFAST64 PRIx64 +# endif +# if !defined PRIXFAST64 || 0 +# undef PRIXFAST64 +# define PRIXFAST64 PRIX64 +# endif +# endif + +# if !defined PRIdMAX || 0 +# undef PRIdMAX +# if 1 +# define PRIdMAX PRId64 +# else +# define PRIdMAX "ld" +# endif +# endif +# if !defined PRIiMAX || 0 +# undef PRIiMAX +# if 1 +# define PRIiMAX PRIi64 +# else +# define PRIiMAX "li" +# endif +# endif +# if !defined PRIoMAX || 0 +# undef PRIoMAX +# if 1 +# define PRIoMAX PRIo64 +# else +# define PRIoMAX "lo" +# endif +# endif +# if !defined PRIuMAX || 0 +# undef PRIuMAX +# if 1 +# define PRIuMAX PRIu64 +# else +# define PRIuMAX "lu" +# endif +# endif +# if !defined PRIxMAX || 0 +# undef PRIxMAX +# if 1 +# define PRIxMAX PRIx64 +# else +# define PRIxMAX "lx" +# endif +# endif +# if !defined PRIXMAX || 0 +# undef PRIXMAX +# if 1 +# define PRIXMAX PRIX64 +# else +# define PRIXMAX "lX" +# endif +# endif + +# if !defined PRIdPTR || 0 +# undef PRIdPTR +# ifdef INTPTR_MAX +# define PRIdPTR "l" "d" +# endif +# endif +# if !defined PRIiPTR || 0 +# undef PRIiPTR +# ifdef INTPTR_MAX +# define PRIiPTR "l" "i" +# endif +# endif +# if !defined PRIoPTR || 0 +# undef PRIoPTR +# ifdef UINTPTR_MAX +# define PRIoPTR "l" "o" +# endif +# endif +# if !defined PRIuPTR || 0 +# undef PRIuPTR +# ifdef UINTPTR_MAX +# define PRIuPTR "l" "u" +# endif +# endif +# if !defined PRIxPTR || 0 +# undef PRIxPTR +# ifdef UINTPTR_MAX +# define PRIxPTR "l" "x" +# endif +# endif +# if !defined PRIXPTR || 0 +# undef PRIXPTR +# ifdef UINTPTR_MAX +# define PRIXPTR "l" "X" +# endif +# endif + +# if !defined SCNd8 || 0 +# undef SCNd8 +# ifdef INT8_MAX +# define SCNd8 "hhd" +# endif +# endif +# if !defined SCNi8 || 0 +# undef SCNi8 +# ifdef INT8_MAX +# define SCNi8 "hhi" +# endif +# endif +# if !defined SCNo8 || 0 +# undef SCNo8 +# ifdef UINT8_MAX +# define SCNo8 "hho" +# endif +# endif +# if !defined SCNu8 || 0 +# undef SCNu8 +# ifdef UINT8_MAX +# define SCNu8 "hhu" +# endif +# endif +# if !defined SCNx8 || 0 +# undef SCNx8 +# ifdef UINT8_MAX +# define SCNx8 "hhx" +# endif +# endif +# if !defined SCNd16 || 0 +# undef SCNd16 +# ifdef INT16_MAX +# define SCNd16 "hd" +# endif +# endif +# if !defined SCNi16 || 0 +# undef SCNi16 +# ifdef INT16_MAX +# define SCNi16 "hi" +# endif +# endif +# if !defined SCNo16 || 0 +# undef SCNo16 +# ifdef UINT16_MAX +# define SCNo16 "ho" +# endif +# endif +# if !defined SCNu16 || 0 +# undef SCNu16 +# ifdef UINT16_MAX +# define SCNu16 "hu" +# endif +# endif +# if !defined SCNx16 || 0 +# undef SCNx16 +# ifdef UINT16_MAX +# define SCNx16 "hx" +# endif +# endif +# if !defined SCNd32 || 0 +# undef SCNd32 +# ifdef INT32_MAX +# define SCNd32 "d" +# endif +# endif +# if !defined SCNi32 || 0 +# undef SCNi32 +# ifdef INT32_MAX +# define SCNi32 "i" +# endif +# endif +# if !defined SCNo32 || 0 +# undef SCNo32 +# ifdef UINT32_MAX +# define SCNo32 "o" +# endif +# endif +# if !defined SCNu32 || 0 +# undef SCNu32 +# ifdef UINT32_MAX +# define SCNu32 "u" +# endif +# endif +# if !defined SCNx32 || 0 +# undef SCNx32 +# ifdef UINT32_MAX +# define SCNx32 "x" +# endif +# endif +# ifdef INT64_MAX +# if 0 +# define _SCN64_PREFIX "l" +# elif defined _MSC_VER || defined __MINGW32__ +# define _SCN64_PREFIX "I64" +# elif 1 && LONG_MAX >> 30 == 1 +# define _SCN64_PREFIX _LONG_LONG_FORMAT_PREFIX +# endif +# if !defined SCNd64 || 0 +# undef SCNd64 +# define SCNd64 _SCN64_PREFIX "d" +# endif +# if !defined SCNi64 || 0 +# undef SCNi64 +# define SCNi64 _SCN64_PREFIX "i" +# endif +# endif +# ifdef UINT64_MAX +# if 0 +# define _SCNu64_PREFIX "l" +# elif defined _MSC_VER || defined __MINGW32__ +# define _SCNu64_PREFIX "I64" +# elif 1 && ULONG_MAX >> 31 == 1 +# define _SCNu64_PREFIX _LONG_LONG_FORMAT_PREFIX +# endif +# if !defined SCNo64 || 0 +# undef SCNo64 +# define SCNo64 _SCNu64_PREFIX "o" +# endif +# if !defined SCNu64 || 0 +# undef SCNu64 +# define SCNu64 _SCNu64_PREFIX "u" +# endif +# if !defined SCNx64 || 0 +# undef SCNx64 +# define SCNx64 _SCNu64_PREFIX "x" +# endif +# endif + +# if !defined SCNdLEAST8 || 0 +# undef SCNdLEAST8 +# define SCNdLEAST8 "hhd" +# endif +# if !defined SCNiLEAST8 || 0 +# undef SCNiLEAST8 +# define SCNiLEAST8 "hhi" +# endif +# if !defined SCNoLEAST8 || 0 +# undef SCNoLEAST8 +# define SCNoLEAST8 "hho" +# endif +# if !defined SCNuLEAST8 || 0 +# undef SCNuLEAST8 +# define SCNuLEAST8 "hhu" +# endif +# if !defined SCNxLEAST8 || 0 +# undef SCNxLEAST8 +# define SCNxLEAST8 "hhx" +# endif +# if !defined SCNdLEAST16 || 0 +# undef SCNdLEAST16 +# define SCNdLEAST16 "hd" +# endif +# if !defined SCNiLEAST16 || 0 +# undef SCNiLEAST16 +# define SCNiLEAST16 "hi" +# endif +# if !defined SCNoLEAST16 || 0 +# undef SCNoLEAST16 +# define SCNoLEAST16 "ho" +# endif +# if !defined SCNuLEAST16 || 0 +# undef SCNuLEAST16 +# define SCNuLEAST16 "hu" +# endif +# if !defined SCNxLEAST16 || 0 +# undef SCNxLEAST16 +# define SCNxLEAST16 "hx" +# endif +# if !defined SCNdLEAST32 || 0 +# undef SCNdLEAST32 +# define SCNdLEAST32 "d" +# endif +# if !defined SCNiLEAST32 || 0 +# undef SCNiLEAST32 +# define SCNiLEAST32 "i" +# endif +# if !defined SCNoLEAST32 || 0 +# undef SCNoLEAST32 +# define SCNoLEAST32 "o" +# endif +# if !defined SCNuLEAST32 || 0 +# undef SCNuLEAST32 +# define SCNuLEAST32 "u" +# endif +# if !defined SCNxLEAST32 || 0 +# undef SCNxLEAST32 +# define SCNxLEAST32 "x" +# endif +# ifdef INT64_MAX +# if !defined SCNdLEAST64 || 0 +# undef SCNdLEAST64 +# define SCNdLEAST64 SCNd64 +# endif +# if !defined SCNiLEAST64 || 0 +# undef SCNiLEAST64 +# define SCNiLEAST64 SCNi64 +# endif +# endif +# ifdef UINT64_MAX +# if !defined SCNoLEAST64 || 0 +# undef SCNoLEAST64 +# define SCNoLEAST64 SCNo64 +# endif +# if !defined SCNuLEAST64 || 0 +# undef SCNuLEAST64 +# define SCNuLEAST64 SCNu64 +# endif +# if !defined SCNxLEAST64 || 0 +# undef SCNxLEAST64 +# define SCNxLEAST64 SCNx64 +# endif +# endif + +# if !defined SCNdFAST8 || 0 +# undef SCNdFAST8 +# if INT_FAST8_MAX > INT32_MAX +# define SCNdFAST8 SCNd64 +# elif INT_FAST8_MAX == 0x7fff +# define SCNdFAST8 "hd" +# elif INT_FAST8_MAX == 0x7f +# define SCNdFAST8 "hhd" +# else +# define SCNdFAST8 "d" +# endif +# endif +# if !defined SCNiFAST8 || 0 +# undef SCNiFAST8 +# if INT_FAST8_MAX > INT32_MAX +# define SCNiFAST8 SCNi64 +# elif INT_FAST8_MAX == 0x7fff +# define SCNiFAST8 "hi" +# elif INT_FAST8_MAX == 0x7f +# define SCNiFAST8 "hhi" +# else +# define SCNiFAST8 "i" +# endif +# endif +# if !defined SCNoFAST8 || 0 +# undef SCNoFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define SCNoFAST8 SCNo64 +# elif UINT_FAST8_MAX == 0xffff +# define SCNoFAST8 "ho" +# elif UINT_FAST8_MAX == 0xff +# define SCNoFAST8 "hho" +# else +# define SCNoFAST8 "o" +# endif +# endif +# if !defined SCNuFAST8 || 0 +# undef SCNuFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define SCNuFAST8 SCNu64 +# elif UINT_FAST8_MAX == 0xffff +# define SCNuFAST8 "hu" +# elif UINT_FAST8_MAX == 0xff +# define SCNuFAST8 "hhu" +# else +# define SCNuFAST8 "u" +# endif +# endif +# if !defined SCNxFAST8 || 0 +# undef SCNxFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define SCNxFAST8 SCNx64 +# elif UINT_FAST8_MAX == 0xffff +# define SCNxFAST8 "hx" +# elif UINT_FAST8_MAX == 0xff +# define SCNxFAST8 "hhx" +# else +# define SCNxFAST8 "x" +# endif +# endif +# if !defined SCNdFAST16 || 0 +# undef SCNdFAST16 +# if INT_FAST16_MAX > INT32_MAX +# define SCNdFAST16 SCNd64 +# elif INT_FAST16_MAX == 0x7fff +# define SCNdFAST16 "hd" +# else +# define SCNdFAST16 "d" +# endif +# endif +# if !defined SCNiFAST16 || 0 +# undef SCNiFAST16 +# if INT_FAST16_MAX > INT32_MAX +# define SCNiFAST16 SCNi64 +# elif INT_FAST16_MAX == 0x7fff +# define SCNiFAST16 "hi" +# else +# define SCNiFAST16 "i" +# endif +# endif +# if !defined SCNoFAST16 || 0 +# undef SCNoFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define SCNoFAST16 SCNo64 +# elif UINT_FAST16_MAX == 0xffff +# define SCNoFAST16 "ho" +# else +# define SCNoFAST16 "o" +# endif +# endif +# if !defined SCNuFAST16 || 0 +# undef SCNuFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define SCNuFAST16 SCNu64 +# elif UINT_FAST16_MAX == 0xffff +# define SCNuFAST16 "hu" +# else +# define SCNuFAST16 "u" +# endif +# endif +# if !defined SCNxFAST16 || 0 +# undef SCNxFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define SCNxFAST16 SCNx64 +# elif UINT_FAST16_MAX == 0xffff +# define SCNxFAST16 "hx" +# else +# define SCNxFAST16 "x" +# endif +# endif +# if !defined SCNdFAST32 || 0 +# undef SCNdFAST32 +# if INT_FAST32_MAX > INT32_MAX +# define SCNdFAST32 SCNd64 +# else +# define SCNdFAST32 "d" +# endif +# endif +# if !defined SCNiFAST32 || 0 +# undef SCNiFAST32 +# if INT_FAST32_MAX > INT32_MAX +# define SCNiFAST32 SCNi64 +# else +# define SCNiFAST32 "i" +# endif +# endif +# if !defined SCNoFAST32 || 0 +# undef SCNoFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define SCNoFAST32 SCNo64 +# else +# define SCNoFAST32 "o" +# endif +# endif +# if !defined SCNuFAST32 || 0 +# undef SCNuFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define SCNuFAST32 SCNu64 +# else +# define SCNuFAST32 "u" +# endif +# endif +# if !defined SCNxFAST32 || 0 +# undef SCNxFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define SCNxFAST32 SCNx64 +# else +# define SCNxFAST32 "x" +# endif +# endif +# ifdef INT64_MAX +# if !defined SCNdFAST64 || 0 +# undef SCNdFAST64 +# define SCNdFAST64 SCNd64 +# endif +# if !defined SCNiFAST64 || 0 +# undef SCNiFAST64 +# define SCNiFAST64 SCNi64 +# endif +# endif +# ifdef UINT64_MAX +# if !defined SCNoFAST64 || 0 +# undef SCNoFAST64 +# define SCNoFAST64 SCNo64 +# endif +# if !defined SCNuFAST64 || 0 +# undef SCNuFAST64 +# define SCNuFAST64 SCNu64 +# endif +# if !defined SCNxFAST64 || 0 +# undef SCNxFAST64 +# define SCNxFAST64 SCNx64 +# endif +# endif + +# if !defined SCNdMAX || 0 +# undef SCNdMAX +# if 1 +# define SCNdMAX SCNd64 +# else +# define SCNdMAX "ld" +# endif +# endif +# if !defined SCNiMAX || 0 +# undef SCNiMAX +# if 1 +# define SCNiMAX SCNi64 +# else +# define SCNiMAX "li" +# endif +# endif +# if !defined SCNoMAX || 0 +# undef SCNoMAX +# if 1 +# define SCNoMAX SCNo64 +# else +# define SCNoMAX "lo" +# endif +# endif +# if !defined SCNuMAX || 0 +# undef SCNuMAX +# if 1 +# define SCNuMAX SCNu64 +# else +# define SCNuMAX "lu" +# endif +# endif +# if !defined SCNxMAX || 0 +# undef SCNxMAX +# if 1 +# define SCNxMAX SCNx64 +# else +# define SCNxMAX "lx" +# endif +# endif + +# if !defined SCNdPTR || 0 +# undef SCNdPTR +# ifdef INTPTR_MAX +# define SCNdPTR "l" "d" +# endif +# endif +# if !defined SCNiPTR || 0 +# undef SCNiPTR +# ifdef INTPTR_MAX +# define SCNiPTR "l" "i" +# endif +# endif +# if !defined SCNoPTR || 0 +# undef SCNoPTR +# ifdef UINTPTR_MAX +# define SCNoPTR "l" "o" +# endif +# endif +# if !defined SCNuPTR || 0 +# undef SCNuPTR +# ifdef UINTPTR_MAX +# define SCNuPTR "l" "u" +# endif +# endif +# if !defined SCNxPTR || 0 +# undef SCNxPTR +# ifdef UINTPTR_MAX +# define SCNxPTR "l" "x" +# endif +# endif + +#endif + +/* 7.8.2 Functions for greatest-width integer types */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if 0 +# if !1 +extern intmax_t imaxabs (intmax_t); +# endif +#elif defined GNULIB_POSIXCHECK +# undef imaxabs +# define imaxabs(a) \ + (GL_LINK_WARNING ("imaxabs is unportable - " \ + "use gnulib module imaxabs for portability"), \ + imaxabs (a)) +#endif + +#if 0 +# if !1 +typedef struct { intmax_t quot; intmax_t rem; } imaxdiv_t; +extern imaxdiv_t imaxdiv (intmax_t, intmax_t); +# endif +#elif defined GNULIB_POSIXCHECK +# undef imaxdiv +# define imaxdiv(a,b) \ + (GL_LINK_WARNING ("imaxdiv is unportable - " \ + "use gnulib module imaxdiv for portability"), \ + imaxdiv (a, b)) +#endif + +#if 1 +# if !1 +extern intmax_t strtoimax (const char *, char **, int); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strtoimax +# define strtoimax(p,e,b) \ + (GL_LINK_WARNING ("strtoimax is unportable - " \ + "use gnulib module strtoimax for portability"), \ + strtoimax (p, e, b)) +#endif + +#if 1 +# if !1 +extern uintmax_t strtoumax (const char *, char **, int); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strtoumax +# define strtoumax(p,e,b) \ + (GL_LINK_WARNING ("strtoumax is unportable - " \ + "use gnulib module strtoumax for portability"), \ + strtoumax (p, e, b)) +#endif + +/* Don't bother defining or declaring wcstoimax and wcstoumax, since + wide-character functions like this are hardly ever useful. */ + +#ifdef __cplusplus +} +#endif + +#endif /* !defined INTTYPES_H && !defined _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H */ diff --git a/src/bin/findutils/gnulib/lib/inttypes.in.h b/src/bin/findutils/gnulib/lib/inttypes.in.h new file mode 100644 index 0000000000..8a24850562 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/inttypes.in.h @@ -0,0 +1,1095 @@ +/* Copyright (C) 2006-2007 Free Software Foundation, Inc. + Written by Paul Eggert, Bruno Haible, Derek Price. + This file is part of gnulib. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* + * ISO C 99 for platforms that lack it. + * + */ + +/* Include the original if it exists, and if this file + has not been included yet or if this file includes gnulib stdint.h + which in turn includes this file. + The include_next requires a split double-inclusion guard. */ +#if ! defined INTTYPES_H || defined _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H +# if @HAVE_INTTYPES_H@ +# @INCLUDE_NEXT@ @NEXT_INTTYPES_H@ +# endif +#endif + +#if ! defined INTTYPES_H && ! defined _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H +#define INTTYPES_H + +/* Include or the gnulib replacement. */ +#include +/* Get CHAR_BIT. */ +#include + +#if !(INT_MIN == INT32_MIN && INT_MAX == INT32_MAX) +# error "This file assumes that 'int' has exactly 32 bits. Please report your platform and compiler to ." +#endif + +/* The definition of GL_LINK_WARNING is copied here. */ + +/* 7.8.1 Macros for format specifiers */ + +#if ! defined __cplusplus || defined __STDC_FORMAT_MACROS + +# if defined _TNS_R_TARGET + /* Tandem NonStop R series and compatible platforms released before + July 2005 support %Ld but not %lld. */ +# define _LONG_LONG_FORMAT_PREFIX "L" +# else +# define _LONG_LONG_FORMAT_PREFIX "ll" +# endif + +# if !defined PRId8 || @PRI_MACROS_BROKEN@ +# undef PRId8 +# ifdef INT8_MAX +# define PRId8 "d" +# endif +# endif +# if !defined PRIi8 || @PRI_MACROS_BROKEN@ +# undef PRIi8 +# ifdef INT8_MAX +# define PRIi8 "i" +# endif +# endif +# if !defined PRIo8 || @PRI_MACROS_BROKEN@ +# undef PRIo8 +# ifdef UINT8_MAX +# define PRIo8 "o" +# endif +# endif +# if !defined PRIu8 || @PRI_MACROS_BROKEN@ +# undef PRIu8 +# ifdef UINT8_MAX +# define PRIu8 "u" +# endif +# endif +# if !defined PRIx8 || @PRI_MACROS_BROKEN@ +# undef PRIx8 +# ifdef UINT8_MAX +# define PRIx8 "x" +# endif +# endif +# if !defined PRIX8 || @PRI_MACROS_BROKEN@ +# undef PRIX8 +# ifdef UINT8_MAX +# define PRIX8 "X" +# endif +# endif +# if !defined PRId16 || @PRI_MACROS_BROKEN@ +# undef PRId16 +# ifdef INT16_MAX +# define PRId16 "d" +# endif +# endif +# if !defined PRIi16 || @PRI_MACROS_BROKEN@ +# undef PRIi16 +# ifdef INT16_MAX +# define PRIi16 "i" +# endif +# endif +# if !defined PRIo16 || @PRI_MACROS_BROKEN@ +# undef PRIo16 +# ifdef UINT16_MAX +# define PRIo16 "o" +# endif +# endif +# if !defined PRIu16 || @PRI_MACROS_BROKEN@ +# undef PRIu16 +# ifdef UINT16_MAX +# define PRIu16 "u" +# endif +# endif +# if !defined PRIx16 || @PRI_MACROS_BROKEN@ +# undef PRIx16 +# ifdef UINT16_MAX +# define PRIx16 "x" +# endif +# endif +# if !defined PRIX16 || @PRI_MACROS_BROKEN@ +# undef PRIX16 +# ifdef UINT16_MAX +# define PRIX16 "X" +# endif +# endif +# if !defined PRId32 || @PRI_MACROS_BROKEN@ +# undef PRId32 +# ifdef INT32_MAX +# define PRId32 "d" +# endif +# endif +# if !defined PRIi32 || @PRI_MACROS_BROKEN@ +# undef PRIi32 +# ifdef INT32_MAX +# define PRIi32 "i" +# endif +# endif +# if !defined PRIo32 || @PRI_MACROS_BROKEN@ +# undef PRIo32 +# ifdef UINT32_MAX +# define PRIo32 "o" +# endif +# endif +# if !defined PRIu32 || @PRI_MACROS_BROKEN@ +# undef PRIu32 +# ifdef UINT32_MAX +# define PRIu32 "u" +# endif +# endif +# if !defined PRIx32 || @PRI_MACROS_BROKEN@ +# undef PRIx32 +# ifdef UINT32_MAX +# define PRIx32 "x" +# endif +# endif +# if !defined PRIX32 || @PRI_MACROS_BROKEN@ +# undef PRIX32 +# ifdef UINT32_MAX +# define PRIX32 "X" +# endif +# endif +# ifdef INT64_MAX +# if @INT64_MAX_EQ_LONG_MAX@ +# define _PRI64_PREFIX "l" +# elif defined _MSC_VER || defined __MINGW32__ +# define _PRI64_PREFIX "I64" +# elif @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1 +# define _PRI64_PREFIX _LONG_LONG_FORMAT_PREFIX +# endif +# if !defined PRId64 || @PRI_MACROS_BROKEN@ +# undef PRId64 +# define PRId64 _PRI64_PREFIX "d" +# endif +# if !defined PRIi64 || @PRI_MACROS_BROKEN@ +# undef PRIi64 +# define PRIi64 _PRI64_PREFIX "i" +# endif +# endif +# ifdef UINT64_MAX +# if @UINT64_MAX_EQ_ULONG_MAX@ +# define _PRIu64_PREFIX "l" +# elif defined _MSC_VER || defined __MINGW32__ +# define _PRIu64_PREFIX "I64" +# elif @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1 +# define _PRIu64_PREFIX _LONG_LONG_FORMAT_PREFIX +# endif +# if !defined PRIo64 || @PRI_MACROS_BROKEN@ +# undef PRIo64 +# define PRIo64 _PRIu64_PREFIX "o" +# endif +# if !defined PRIu64 || @PRI_MACROS_BROKEN@ +# undef PRIu64 +# define PRIu64 _PRIu64_PREFIX "u" +# endif +# if !defined PRIx64 || @PRI_MACROS_BROKEN@ +# undef PRIx64 +# define PRIx64 _PRIu64_PREFIX "x" +# endif +# if !defined PRIX64 || @PRI_MACROS_BROKEN@ +# undef PRIX64 +# define PRIX64 _PRIu64_PREFIX "X" +# endif +# endif + +# if !defined PRIdLEAST8 || @PRI_MACROS_BROKEN@ +# undef PRIdLEAST8 +# define PRIdLEAST8 "d" +# endif +# if !defined PRIiLEAST8 || @PRI_MACROS_BROKEN@ +# undef PRIiLEAST8 +# define PRIiLEAST8 "i" +# endif +# if !defined PRIoLEAST8 || @PRI_MACROS_BROKEN@ +# undef PRIoLEAST8 +# define PRIoLEAST8 "o" +# endif +# if !defined PRIuLEAST8 || @PRI_MACROS_BROKEN@ +# undef PRIuLEAST8 +# define PRIuLEAST8 "u" +# endif +# if !defined PRIxLEAST8 || @PRI_MACROS_BROKEN@ +# undef PRIxLEAST8 +# define PRIxLEAST8 "x" +# endif +# if !defined PRIXLEAST8 || @PRI_MACROS_BROKEN@ +# undef PRIXLEAST8 +# define PRIXLEAST8 "X" +# endif +# if !defined PRIdLEAST16 || @PRI_MACROS_BROKEN@ +# undef PRIdLEAST16 +# define PRIdLEAST16 "d" +# endif +# if !defined PRIiLEAST16 || @PRI_MACROS_BROKEN@ +# undef PRIiLEAST16 +# define PRIiLEAST16 "i" +# endif +# if !defined PRIoLEAST16 || @PRI_MACROS_BROKEN@ +# undef PRIoLEAST16 +# define PRIoLEAST16 "o" +# endif +# if !defined PRIuLEAST16 || @PRI_MACROS_BROKEN@ +# undef PRIuLEAST16 +# define PRIuLEAST16 "u" +# endif +# if !defined PRIxLEAST16 || @PRI_MACROS_BROKEN@ +# undef PRIxLEAST16 +# define PRIxLEAST16 "x" +# endif +# if !defined PRIXLEAST16 || @PRI_MACROS_BROKEN@ +# undef PRIXLEAST16 +# define PRIXLEAST16 "X" +# endif +# if !defined PRIdLEAST32 || @PRI_MACROS_BROKEN@ +# undef PRIdLEAST32 +# define PRIdLEAST32 "d" +# endif +# if !defined PRIiLEAST32 || @PRI_MACROS_BROKEN@ +# undef PRIiLEAST32 +# define PRIiLEAST32 "i" +# endif +# if !defined PRIoLEAST32 || @PRI_MACROS_BROKEN@ +# undef PRIoLEAST32 +# define PRIoLEAST32 "o" +# endif +# if !defined PRIuLEAST32 || @PRI_MACROS_BROKEN@ +# undef PRIuLEAST32 +# define PRIuLEAST32 "u" +# endif +# if !defined PRIxLEAST32 || @PRI_MACROS_BROKEN@ +# undef PRIxLEAST32 +# define PRIxLEAST32 "x" +# endif +# if !defined PRIXLEAST32 || @PRI_MACROS_BROKEN@ +# undef PRIXLEAST32 +# define PRIXLEAST32 "X" +# endif +# ifdef INT64_MAX +# if !defined PRIdLEAST64 || @PRI_MACROS_BROKEN@ +# undef PRIdLEAST64 +# define PRIdLEAST64 PRId64 +# endif +# if !defined PRIiLEAST64 || @PRI_MACROS_BROKEN@ +# undef PRIiLEAST64 +# define PRIiLEAST64 PRIi64 +# endif +# endif +# ifdef UINT64_MAX +# if !defined PRIoLEAST64 || @PRI_MACROS_BROKEN@ +# undef PRIoLEAST64 +# define PRIoLEAST64 PRIo64 +# endif +# if !defined PRIuLEAST64 || @PRI_MACROS_BROKEN@ +# undef PRIuLEAST64 +# define PRIuLEAST64 PRIu64 +# endif +# if !defined PRIxLEAST64 || @PRI_MACROS_BROKEN@ +# undef PRIxLEAST64 +# define PRIxLEAST64 PRIx64 +# endif +# if !defined PRIXLEAST64 || @PRI_MACROS_BROKEN@ +# undef PRIXLEAST64 +# define PRIXLEAST64 PRIX64 +# endif +# endif + +# if !defined PRIdFAST8 || @PRI_MACROS_BROKEN@ +# undef PRIdFAST8 +# if INT_FAST8_MAX > INT32_MAX +# define PRIdFAST8 PRId64 +# else +# define PRIdFAST8 "d" +# endif +# endif +# if !defined PRIiFAST8 || @PRI_MACROS_BROKEN@ +# undef PRIiFAST8 +# if INT_FAST8_MAX > INT32_MAX +# define PRIiFAST8 PRIi64 +# else +# define PRIiFAST8 "i" +# endif +# endif +# if !defined PRIoFAST8 || @PRI_MACROS_BROKEN@ +# undef PRIoFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define PRIoFAST8 PRIo64 +# else +# define PRIoFAST8 "o" +# endif +# endif +# if !defined PRIuFAST8 || @PRI_MACROS_BROKEN@ +# undef PRIuFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define PRIuFAST8 PRIu64 +# else +# define PRIuFAST8 "u" +# endif +# endif +# if !defined PRIxFAST8 || @PRI_MACROS_BROKEN@ +# undef PRIxFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define PRIxFAST8 PRIx64 +# else +# define PRIxFAST8 "x" +# endif +# endif +# if !defined PRIXFAST8 || @PRI_MACROS_BROKEN@ +# undef PRIXFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define PRIXFAST8 PRIX64 +# else +# define PRIXFAST8 "X" +# endif +# endif +# if !defined PRIdFAST16 || @PRI_MACROS_BROKEN@ +# undef PRIdFAST16 +# if INT_FAST16_MAX > INT32_MAX +# define PRIdFAST16 PRId64 +# else +# define PRIdFAST16 "d" +# endif +# endif +# if !defined PRIiFAST16 || @PRI_MACROS_BROKEN@ +# undef PRIiFAST16 +# if INT_FAST16_MAX > INT32_MAX +# define PRIiFAST16 PRIi64 +# else +# define PRIiFAST16 "i" +# endif +# endif +# if !defined PRIoFAST16 || @PRI_MACROS_BROKEN@ +# undef PRIoFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define PRIoFAST16 PRIo64 +# else +# define PRIoFAST16 "o" +# endif +# endif +# if !defined PRIuFAST16 || @PRI_MACROS_BROKEN@ +# undef PRIuFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define PRIuFAST16 PRIu64 +# else +# define PRIuFAST16 "u" +# endif +# endif +# if !defined PRIxFAST16 || @PRI_MACROS_BROKEN@ +# undef PRIxFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define PRIxFAST16 PRIx64 +# else +# define PRIxFAST16 "x" +# endif +# endif +# if !defined PRIXFAST16 || @PRI_MACROS_BROKEN@ +# undef PRIXFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define PRIXFAST16 PRIX64 +# else +# define PRIXFAST16 "X" +# endif +# endif +# if !defined PRIdFAST32 || @PRI_MACROS_BROKEN@ +# undef PRIdFAST32 +# if INT_FAST32_MAX > INT32_MAX +# define PRIdFAST32 PRId64 +# else +# define PRIdFAST32 "d" +# endif +# endif +# if !defined PRIiFAST32 || @PRI_MACROS_BROKEN@ +# undef PRIiFAST32 +# if INT_FAST32_MAX > INT32_MAX +# define PRIiFAST32 PRIi64 +# else +# define PRIiFAST32 "i" +# endif +# endif +# if !defined PRIoFAST32 || @PRI_MACROS_BROKEN@ +# undef PRIoFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define PRIoFAST32 PRIo64 +# else +# define PRIoFAST32 "o" +# endif +# endif +# if !defined PRIuFAST32 || @PRI_MACROS_BROKEN@ +# undef PRIuFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define PRIuFAST32 PRIu64 +# else +# define PRIuFAST32 "u" +# endif +# endif +# if !defined PRIxFAST32 || @PRI_MACROS_BROKEN@ +# undef PRIxFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define PRIxFAST32 PRIx64 +# else +# define PRIxFAST32 "x" +# endif +# endif +# if !defined PRIXFAST32 || @PRI_MACROS_BROKEN@ +# undef PRIXFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define PRIXFAST32 PRIX64 +# else +# define PRIXFAST32 "X" +# endif +# endif +# ifdef INT64_MAX +# if !defined PRIdFAST64 || @PRI_MACROS_BROKEN@ +# undef PRIdFAST64 +# define PRIdFAST64 PRId64 +# endif +# if !defined PRIiFAST64 || @PRI_MACROS_BROKEN@ +# undef PRIiFAST64 +# define PRIiFAST64 PRIi64 +# endif +# endif +# ifdef UINT64_MAX +# if !defined PRIoFAST64 || @PRI_MACROS_BROKEN@ +# undef PRIoFAST64 +# define PRIoFAST64 PRIo64 +# endif +# if !defined PRIuFAST64 || @PRI_MACROS_BROKEN@ +# undef PRIuFAST64 +# define PRIuFAST64 PRIu64 +# endif +# if !defined PRIxFAST64 || @PRI_MACROS_BROKEN@ +# undef PRIxFAST64 +# define PRIxFAST64 PRIx64 +# endif +# if !defined PRIXFAST64 || @PRI_MACROS_BROKEN@ +# undef PRIXFAST64 +# define PRIXFAST64 PRIX64 +# endif +# endif + +# if !defined PRIdMAX || @PRI_MACROS_BROKEN@ +# undef PRIdMAX +# if @INT32_MAX_LT_INTMAX_MAX@ +# define PRIdMAX PRId64 +# else +# define PRIdMAX "ld" +# endif +# endif +# if !defined PRIiMAX || @PRI_MACROS_BROKEN@ +# undef PRIiMAX +# if @INT32_MAX_LT_INTMAX_MAX@ +# define PRIiMAX PRIi64 +# else +# define PRIiMAX "li" +# endif +# endif +# if !defined PRIoMAX || @PRI_MACROS_BROKEN@ +# undef PRIoMAX +# if @UINT32_MAX_LT_UINTMAX_MAX@ +# define PRIoMAX PRIo64 +# else +# define PRIoMAX "lo" +# endif +# endif +# if !defined PRIuMAX || @PRI_MACROS_BROKEN@ +# undef PRIuMAX +# if @UINT32_MAX_LT_UINTMAX_MAX@ +# define PRIuMAX PRIu64 +# else +# define PRIuMAX "lu" +# endif +# endif +# if !defined PRIxMAX || @PRI_MACROS_BROKEN@ +# undef PRIxMAX +# if @UINT32_MAX_LT_UINTMAX_MAX@ +# define PRIxMAX PRIx64 +# else +# define PRIxMAX "lx" +# endif +# endif +# if !defined PRIXMAX || @PRI_MACROS_BROKEN@ +# undef PRIXMAX +# if @UINT32_MAX_LT_UINTMAX_MAX@ +# define PRIXMAX PRIX64 +# else +# define PRIXMAX "lX" +# endif +# endif + +# if !defined PRIdPTR || @PRI_MACROS_BROKEN@ +# undef PRIdPTR +# ifdef INTPTR_MAX +# define PRIdPTR @PRIPTR_PREFIX@ "d" +# endif +# endif +# if !defined PRIiPTR || @PRI_MACROS_BROKEN@ +# undef PRIiPTR +# ifdef INTPTR_MAX +# define PRIiPTR @PRIPTR_PREFIX@ "i" +# endif +# endif +# if !defined PRIoPTR || @PRI_MACROS_BROKEN@ +# undef PRIoPTR +# ifdef UINTPTR_MAX +# define PRIoPTR @PRIPTR_PREFIX@ "o" +# endif +# endif +# if !defined PRIuPTR || @PRI_MACROS_BROKEN@ +# undef PRIuPTR +# ifdef UINTPTR_MAX +# define PRIuPTR @PRIPTR_PREFIX@ "u" +# endif +# endif +# if !defined PRIxPTR || @PRI_MACROS_BROKEN@ +# undef PRIxPTR +# ifdef UINTPTR_MAX +# define PRIxPTR @PRIPTR_PREFIX@ "x" +# endif +# endif +# if !defined PRIXPTR || @PRI_MACROS_BROKEN@ +# undef PRIXPTR +# ifdef UINTPTR_MAX +# define PRIXPTR @PRIPTR_PREFIX@ "X" +# endif +# endif + +# if !defined SCNd8 || @PRI_MACROS_BROKEN@ +# undef SCNd8 +# ifdef INT8_MAX +# define SCNd8 "hhd" +# endif +# endif +# if !defined SCNi8 || @PRI_MACROS_BROKEN@ +# undef SCNi8 +# ifdef INT8_MAX +# define SCNi8 "hhi" +# endif +# endif +# if !defined SCNo8 || @PRI_MACROS_BROKEN@ +# undef SCNo8 +# ifdef UINT8_MAX +# define SCNo8 "hho" +# endif +# endif +# if !defined SCNu8 || @PRI_MACROS_BROKEN@ +# undef SCNu8 +# ifdef UINT8_MAX +# define SCNu8 "hhu" +# endif +# endif +# if !defined SCNx8 || @PRI_MACROS_BROKEN@ +# undef SCNx8 +# ifdef UINT8_MAX +# define SCNx8 "hhx" +# endif +# endif +# if !defined SCNd16 || @PRI_MACROS_BROKEN@ +# undef SCNd16 +# ifdef INT16_MAX +# define SCNd16 "hd" +# endif +# endif +# if !defined SCNi16 || @PRI_MACROS_BROKEN@ +# undef SCNi16 +# ifdef INT16_MAX +# define SCNi16 "hi" +# endif +# endif +# if !defined SCNo16 || @PRI_MACROS_BROKEN@ +# undef SCNo16 +# ifdef UINT16_MAX +# define SCNo16 "ho" +# endif +# endif +# if !defined SCNu16 || @PRI_MACROS_BROKEN@ +# undef SCNu16 +# ifdef UINT16_MAX +# define SCNu16 "hu" +# endif +# endif +# if !defined SCNx16 || @PRI_MACROS_BROKEN@ +# undef SCNx16 +# ifdef UINT16_MAX +# define SCNx16 "hx" +# endif +# endif +# if !defined SCNd32 || @PRI_MACROS_BROKEN@ +# undef SCNd32 +# ifdef INT32_MAX +# define SCNd32 "d" +# endif +# endif +# if !defined SCNi32 || @PRI_MACROS_BROKEN@ +# undef SCNi32 +# ifdef INT32_MAX +# define SCNi32 "i" +# endif +# endif +# if !defined SCNo32 || @PRI_MACROS_BROKEN@ +# undef SCNo32 +# ifdef UINT32_MAX +# define SCNo32 "o" +# endif +# endif +# if !defined SCNu32 || @PRI_MACROS_BROKEN@ +# undef SCNu32 +# ifdef UINT32_MAX +# define SCNu32 "u" +# endif +# endif +# if !defined SCNx32 || @PRI_MACROS_BROKEN@ +# undef SCNx32 +# ifdef UINT32_MAX +# define SCNx32 "x" +# endif +# endif +# ifdef INT64_MAX +# if @INT64_MAX_EQ_LONG_MAX@ +# define _SCN64_PREFIX "l" +# elif defined _MSC_VER || defined __MINGW32__ +# define _SCN64_PREFIX "I64" +# elif @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1 +# define _SCN64_PREFIX _LONG_LONG_FORMAT_PREFIX +# endif +# if !defined SCNd64 || @PRI_MACROS_BROKEN@ +# undef SCNd64 +# define SCNd64 _SCN64_PREFIX "d" +# endif +# if !defined SCNi64 || @PRI_MACROS_BROKEN@ +# undef SCNi64 +# define SCNi64 _SCN64_PREFIX "i" +# endif +# endif +# ifdef UINT64_MAX +# if @UINT64_MAX_EQ_ULONG_MAX@ +# define _SCNu64_PREFIX "l" +# elif defined _MSC_VER || defined __MINGW32__ +# define _SCNu64_PREFIX "I64" +# elif @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1 +# define _SCNu64_PREFIX _LONG_LONG_FORMAT_PREFIX +# endif +# if !defined SCNo64 || @PRI_MACROS_BROKEN@ +# undef SCNo64 +# define SCNo64 _SCNu64_PREFIX "o" +# endif +# if !defined SCNu64 || @PRI_MACROS_BROKEN@ +# undef SCNu64 +# define SCNu64 _SCNu64_PREFIX "u" +# endif +# if !defined SCNx64 || @PRI_MACROS_BROKEN@ +# undef SCNx64 +# define SCNx64 _SCNu64_PREFIX "x" +# endif +# endif + +# if !defined SCNdLEAST8 || @PRI_MACROS_BROKEN@ +# undef SCNdLEAST8 +# define SCNdLEAST8 "hhd" +# endif +# if !defined SCNiLEAST8 || @PRI_MACROS_BROKEN@ +# undef SCNiLEAST8 +# define SCNiLEAST8 "hhi" +# endif +# if !defined SCNoLEAST8 || @PRI_MACROS_BROKEN@ +# undef SCNoLEAST8 +# define SCNoLEAST8 "hho" +# endif +# if !defined SCNuLEAST8 || @PRI_MACROS_BROKEN@ +# undef SCNuLEAST8 +# define SCNuLEAST8 "hhu" +# endif +# if !defined SCNxLEAST8 || @PRI_MACROS_BROKEN@ +# undef SCNxLEAST8 +# define SCNxLEAST8 "hhx" +# endif +# if !defined SCNdLEAST16 || @PRI_MACROS_BROKEN@ +# undef SCNdLEAST16 +# define SCNdLEAST16 "hd" +# endif +# if !defined SCNiLEAST16 || @PRI_MACROS_BROKEN@ +# undef SCNiLEAST16 +# define SCNiLEAST16 "hi" +# endif +# if !defined SCNoLEAST16 || @PRI_MACROS_BROKEN@ +# undef SCNoLEAST16 +# define SCNoLEAST16 "ho" +# endif +# if !defined SCNuLEAST16 || @PRI_MACROS_BROKEN@ +# undef SCNuLEAST16 +# define SCNuLEAST16 "hu" +# endif +# if !defined SCNxLEAST16 || @PRI_MACROS_BROKEN@ +# undef SCNxLEAST16 +# define SCNxLEAST16 "hx" +# endif +# if !defined SCNdLEAST32 || @PRI_MACROS_BROKEN@ +# undef SCNdLEAST32 +# define SCNdLEAST32 "d" +# endif +# if !defined SCNiLEAST32 || @PRI_MACROS_BROKEN@ +# undef SCNiLEAST32 +# define SCNiLEAST32 "i" +# endif +# if !defined SCNoLEAST32 || @PRI_MACROS_BROKEN@ +# undef SCNoLEAST32 +# define SCNoLEAST32 "o" +# endif +# if !defined SCNuLEAST32 || @PRI_MACROS_BROKEN@ +# undef SCNuLEAST32 +# define SCNuLEAST32 "u" +# endif +# if !defined SCNxLEAST32 || @PRI_MACROS_BROKEN@ +# undef SCNxLEAST32 +# define SCNxLEAST32 "x" +# endif +# ifdef INT64_MAX +# if !defined SCNdLEAST64 || @PRI_MACROS_BROKEN@ +# undef SCNdLEAST64 +# define SCNdLEAST64 SCNd64 +# endif +# if !defined SCNiLEAST64 || @PRI_MACROS_BROKEN@ +# undef SCNiLEAST64 +# define SCNiLEAST64 SCNi64 +# endif +# endif +# ifdef UINT64_MAX +# if !defined SCNoLEAST64 || @PRI_MACROS_BROKEN@ +# undef SCNoLEAST64 +# define SCNoLEAST64 SCNo64 +# endif +# if !defined SCNuLEAST64 || @PRI_MACROS_BROKEN@ +# undef SCNuLEAST64 +# define SCNuLEAST64 SCNu64 +# endif +# if !defined SCNxLEAST64 || @PRI_MACROS_BROKEN@ +# undef SCNxLEAST64 +# define SCNxLEAST64 SCNx64 +# endif +# endif + +# if !defined SCNdFAST8 || @PRI_MACROS_BROKEN@ +# undef SCNdFAST8 +# if INT_FAST8_MAX > INT32_MAX +# define SCNdFAST8 SCNd64 +# elif INT_FAST8_MAX == 0x7fff +# define SCNdFAST8 "hd" +# elif INT_FAST8_MAX == 0x7f +# define SCNdFAST8 "hhd" +# else +# define SCNdFAST8 "d" +# endif +# endif +# if !defined SCNiFAST8 || @PRI_MACROS_BROKEN@ +# undef SCNiFAST8 +# if INT_FAST8_MAX > INT32_MAX +# define SCNiFAST8 SCNi64 +# elif INT_FAST8_MAX == 0x7fff +# define SCNiFAST8 "hi" +# elif INT_FAST8_MAX == 0x7f +# define SCNiFAST8 "hhi" +# else +# define SCNiFAST8 "i" +# endif +# endif +# if !defined SCNoFAST8 || @PRI_MACROS_BROKEN@ +# undef SCNoFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define SCNoFAST8 SCNo64 +# elif UINT_FAST8_MAX == 0xffff +# define SCNoFAST8 "ho" +# elif UINT_FAST8_MAX == 0xff +# define SCNoFAST8 "hho" +# else +# define SCNoFAST8 "o" +# endif +# endif +# if !defined SCNuFAST8 || @PRI_MACROS_BROKEN@ +# undef SCNuFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define SCNuFAST8 SCNu64 +# elif UINT_FAST8_MAX == 0xffff +# define SCNuFAST8 "hu" +# elif UINT_FAST8_MAX == 0xff +# define SCNuFAST8 "hhu" +# else +# define SCNuFAST8 "u" +# endif +# endif +# if !defined SCNxFAST8 || @PRI_MACROS_BROKEN@ +# undef SCNxFAST8 +# if UINT_FAST8_MAX > UINT32_MAX +# define SCNxFAST8 SCNx64 +# elif UINT_FAST8_MAX == 0xffff +# define SCNxFAST8 "hx" +# elif UINT_FAST8_MAX == 0xff +# define SCNxFAST8 "hhx" +# else +# define SCNxFAST8 "x" +# endif +# endif +# if !defined SCNdFAST16 || @PRI_MACROS_BROKEN@ +# undef SCNdFAST16 +# if INT_FAST16_MAX > INT32_MAX +# define SCNdFAST16 SCNd64 +# elif INT_FAST16_MAX == 0x7fff +# define SCNdFAST16 "hd" +# else +# define SCNdFAST16 "d" +# endif +# endif +# if !defined SCNiFAST16 || @PRI_MACROS_BROKEN@ +# undef SCNiFAST16 +# if INT_FAST16_MAX > INT32_MAX +# define SCNiFAST16 SCNi64 +# elif INT_FAST16_MAX == 0x7fff +# define SCNiFAST16 "hi" +# else +# define SCNiFAST16 "i" +# endif +# endif +# if !defined SCNoFAST16 || @PRI_MACROS_BROKEN@ +# undef SCNoFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define SCNoFAST16 SCNo64 +# elif UINT_FAST16_MAX == 0xffff +# define SCNoFAST16 "ho" +# else +# define SCNoFAST16 "o" +# endif +# endif +# if !defined SCNuFAST16 || @PRI_MACROS_BROKEN@ +# undef SCNuFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define SCNuFAST16 SCNu64 +# elif UINT_FAST16_MAX == 0xffff +# define SCNuFAST16 "hu" +# else +# define SCNuFAST16 "u" +# endif +# endif +# if !defined SCNxFAST16 || @PRI_MACROS_BROKEN@ +# undef SCNxFAST16 +# if UINT_FAST16_MAX > UINT32_MAX +# define SCNxFAST16 SCNx64 +# elif UINT_FAST16_MAX == 0xffff +# define SCNxFAST16 "hx" +# else +# define SCNxFAST16 "x" +# endif +# endif +# if !defined SCNdFAST32 || @PRI_MACROS_BROKEN@ +# undef SCNdFAST32 +# if INT_FAST32_MAX > INT32_MAX +# define SCNdFAST32 SCNd64 +# else +# define SCNdFAST32 "d" +# endif +# endif +# if !defined SCNiFAST32 || @PRI_MACROS_BROKEN@ +# undef SCNiFAST32 +# if INT_FAST32_MAX > INT32_MAX +# define SCNiFAST32 SCNi64 +# else +# define SCNiFAST32 "i" +# endif +# endif +# if !defined SCNoFAST32 || @PRI_MACROS_BROKEN@ +# undef SCNoFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define SCNoFAST32 SCNo64 +# else +# define SCNoFAST32 "o" +# endif +# endif +# if !defined SCNuFAST32 || @PRI_MACROS_BROKEN@ +# undef SCNuFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define SCNuFAST32 SCNu64 +# else +# define SCNuFAST32 "u" +# endif +# endif +# if !defined SCNxFAST32 || @PRI_MACROS_BROKEN@ +# undef SCNxFAST32 +# if UINT_FAST32_MAX > UINT32_MAX +# define SCNxFAST32 SCNx64 +# else +# define SCNxFAST32 "x" +# endif +# endif +# ifdef INT64_MAX +# if !defined SCNdFAST64 || @PRI_MACROS_BROKEN@ +# undef SCNdFAST64 +# define SCNdFAST64 SCNd64 +# endif +# if !defined SCNiFAST64 || @PRI_MACROS_BROKEN@ +# undef SCNiFAST64 +# define SCNiFAST64 SCNi64 +# endif +# endif +# ifdef UINT64_MAX +# if !defined SCNoFAST64 || @PRI_MACROS_BROKEN@ +# undef SCNoFAST64 +# define SCNoFAST64 SCNo64 +# endif +# if !defined SCNuFAST64 || @PRI_MACROS_BROKEN@ +# undef SCNuFAST64 +# define SCNuFAST64 SCNu64 +# endif +# if !defined SCNxFAST64 || @PRI_MACROS_BROKEN@ +# undef SCNxFAST64 +# define SCNxFAST64 SCNx64 +# endif +# endif + +# if !defined SCNdMAX || @PRI_MACROS_BROKEN@ +# undef SCNdMAX +# if @INT32_MAX_LT_INTMAX_MAX@ +# define SCNdMAX SCNd64 +# else +# define SCNdMAX "ld" +# endif +# endif +# if !defined SCNiMAX || @PRI_MACROS_BROKEN@ +# undef SCNiMAX +# if @INT32_MAX_LT_INTMAX_MAX@ +# define SCNiMAX SCNi64 +# else +# define SCNiMAX "li" +# endif +# endif +# if !defined SCNoMAX || @PRI_MACROS_BROKEN@ +# undef SCNoMAX +# if @UINT32_MAX_LT_UINTMAX_MAX@ +# define SCNoMAX SCNo64 +# else +# define SCNoMAX "lo" +# endif +# endif +# if !defined SCNuMAX || @PRI_MACROS_BROKEN@ +# undef SCNuMAX +# if @UINT32_MAX_LT_UINTMAX_MAX@ +# define SCNuMAX SCNu64 +# else +# define SCNuMAX "lu" +# endif +# endif +# if !defined SCNxMAX || @PRI_MACROS_BROKEN@ +# undef SCNxMAX +# if @UINT32_MAX_LT_UINTMAX_MAX@ +# define SCNxMAX SCNx64 +# else +# define SCNxMAX "lx" +# endif +# endif + +# if !defined SCNdPTR || @PRI_MACROS_BROKEN@ +# undef SCNdPTR +# ifdef INTPTR_MAX +# define SCNdPTR @PRIPTR_PREFIX@ "d" +# endif +# endif +# if !defined SCNiPTR || @PRI_MACROS_BROKEN@ +# undef SCNiPTR +# ifdef INTPTR_MAX +# define SCNiPTR @PRIPTR_PREFIX@ "i" +# endif +# endif +# if !defined SCNoPTR || @PRI_MACROS_BROKEN@ +# undef SCNoPTR +# ifdef UINTPTR_MAX +# define SCNoPTR @PRIPTR_PREFIX@ "o" +# endif +# endif +# if !defined SCNuPTR || @PRI_MACROS_BROKEN@ +# undef SCNuPTR +# ifdef UINTPTR_MAX +# define SCNuPTR @PRIPTR_PREFIX@ "u" +# endif +# endif +# if !defined SCNxPTR || @PRI_MACROS_BROKEN@ +# undef SCNxPTR +# ifdef UINTPTR_MAX +# define SCNxPTR @PRIPTR_PREFIX@ "x" +# endif +# endif + +#endif + +/* 7.8.2 Functions for greatest-width integer types */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if @GNULIB_IMAXABS@ +# if !@HAVE_DECL_IMAXABS@ +extern intmax_t imaxabs (intmax_t); +# endif +#elif defined GNULIB_POSIXCHECK +# undef imaxabs +# define imaxabs(a) \ + (GL_LINK_WARNING ("imaxabs is unportable - " \ + "use gnulib module imaxabs for portability"), \ + imaxabs (a)) +#endif + +#if @GNULIB_IMAXDIV@ +# if !@HAVE_DECL_IMAXDIV@ +typedef struct { intmax_t quot; intmax_t rem; } imaxdiv_t; +extern imaxdiv_t imaxdiv (intmax_t, intmax_t); +# endif +#elif defined GNULIB_POSIXCHECK +# undef imaxdiv +# define imaxdiv(a,b) \ + (GL_LINK_WARNING ("imaxdiv is unportable - " \ + "use gnulib module imaxdiv for portability"), \ + imaxdiv (a, b)) +#endif + +#if @GNULIB_STRTOIMAX@ +# if !@HAVE_DECL_STRTOIMAX@ +extern intmax_t strtoimax (const char *, char **, int); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strtoimax +# define strtoimax(p,e,b) \ + (GL_LINK_WARNING ("strtoimax is unportable - " \ + "use gnulib module strtoimax for portability"), \ + strtoimax (p, e, b)) +#endif + +#if @GNULIB_STRTOUMAX@ +# if !@HAVE_DECL_STRTOUMAX@ +extern uintmax_t strtoumax (const char *, char **, int); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strtoumax +# define strtoumax(p,e,b) \ + (GL_LINK_WARNING ("strtoumax is unportable - " \ + "use gnulib module strtoumax for portability"), \ + strtoumax (p, e, b)) +#endif + +/* Don't bother defining or declaring wcstoimax and wcstoumax, since + wide-character functions like this are hardly ever useful. */ + +#ifdef __cplusplus +} +#endif + +#endif /* !defined INTTYPES_H && !defined _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H */ diff --git a/src/bin/findutils/gnulib/lib/lchown.c b/src/bin/findutils/gnulib/lib/lchown.c new file mode 100644 index 0000000000..07aef87394 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/lchown.c @@ -0,0 +1,62 @@ +/* Provide a stub lchown function for systems that lack it. + + Copyright (C) 1998, 1999, 2002, 2004, 2006, 2007 Free Software + Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include + +/* If the system chown does not follow symlinks, we don't want it + replaced by gnulib's chown, which does follow symlinks. */ +#if CHOWN_MODIFIES_SYMLINK +# define REPLACE_CHOWN 0 +#endif +#include + +#include +#include + +/* Some systems don't have EOPNOTSUPP. */ +#ifndef EOPNOTSUPP +# ifdef ENOTSUP +# define EOPNOTSUPP ENOTSUP +# else +/* Some systems don't have ENOTSUP either. */ +# define EOPNOTSUPP EINVAL +# endif +#endif + +/* Work just like chown, except when FILE is a symbolic link. + In that case, set errno to EOPNOTSUPP and return -1. + But if autoconf tests determined that chown modifies + symlinks, then just call chown. */ + +int +lchown (const char *file, uid_t uid, gid_t gid) +{ +#if ! CHOWN_MODIFIES_SYMLINK + struct stat stats; + + if (lstat (file, &stats) == 0 && S_ISLNK (stats.st_mode)) + { + errno = EOPNOTSUPP; + return -1; + } +#endif + + return chown (file, uid, gid); +} diff --git a/src/bin/findutils/gnulib/lib/localcharset.c b/src/bin/findutils/gnulib/lib/localcharset.c new file mode 100644 index 0000000000..4f319487f9 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/localcharset.c @@ -0,0 +1,460 @@ +/* Determine a canonical name for the current locale's character encoding. + + Copyright (C) 2000-2006 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* Written by Bruno Haible . */ + +#include + +/* Specification. */ +#include "localcharset.h" + +#include +#include +#include +#include + +#if defined _WIN32 || defined __WIN32__ +# define WIN32_NATIVE +#endif + +#if defined __EMX__ +/* Assume EMX program runs on OS/2, even if compiled under DOS. */ +# define OS2 +#endif + +#if !defined WIN32_NATIVE +# if HAVE_LANGINFO_CODESET +# include +# else +# if 0 /* see comment below */ +# include +# endif +# endif +# ifdef __CYGWIN__ +# define WIN32_LEAN_AND_MEAN +# include +# endif +#elif defined WIN32_NATIVE +# define WIN32_LEAN_AND_MEAN +# include +#endif +#if defined OS2 +# define INCL_DOS +# include +#endif + +#if ENABLE_RELOCATABLE +# include "relocatable.h" +#else +# define relocate(pathname) (pathname) +#endif + +/* Get LIBDIR. */ +#ifndef LIBDIR +# include "configmake.h" +#endif + +#if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__ + /* Win32, Cygwin, OS/2, DOS */ +# define ISSLASH(C) ((C) == '/' || (C) == '\\') +#endif + +#ifndef DIRECTORY_SEPARATOR +# define DIRECTORY_SEPARATOR '/' +#endif + +#ifndef ISSLASH +# define ISSLASH(C) ((C) == DIRECTORY_SEPARATOR) +#endif + +#if HAVE_DECL_GETC_UNLOCKED +# undef getc +# define getc getc_unlocked +#endif + +/* The following static variable is declared 'volatile' to avoid a + possible multithread problem in the function get_charset_aliases. If we + are running in a threaded environment, and if two threads initialize + 'charset_aliases' simultaneously, both will produce the same value, + and everything will be ok if the two assignments to 'charset_aliases' + are atomic. But I don't know what will happen if the two assignments mix. */ +#if __STDC__ != 1 +# define volatile /* empty */ +#endif +/* Pointer to the contents of the charset.alias file, if it has already been + read, else NULL. Its format is: + ALIAS_1 '\0' CANONICAL_1 '\0' ... ALIAS_n '\0' CANONICAL_n '\0' '\0' */ +static const char * volatile charset_aliases; + +/* Return a pointer to the contents of the charset.alias file. */ +static const char * +get_charset_aliases (void) +{ + const char *cp; + + cp = charset_aliases; + if (cp == NULL) + { +#if !(defined VMS || defined WIN32_NATIVE || defined __CYGWIN__) + FILE *fp; + const char *dir; + const char *base = "charset.alias"; + char *file_name; + + /* Make it possible to override the charset.alias location. This is + necessary for running the testsuite before "make install". */ + dir = getenv ("CHARSETALIASDIR"); + if (dir == NULL || dir[0] == '\0') + dir = relocate (LIBDIR); + + /* Concatenate dir and base into freshly allocated file_name. */ + { + size_t dir_len = strlen (dir); + size_t base_len = strlen (base); + int add_slash = (dir_len > 0 && !ISSLASH (dir[dir_len - 1])); + file_name = (char *) malloc (dir_len + add_slash + base_len + 1); + if (file_name != NULL) + { + memcpy (file_name, dir, dir_len); + if (add_slash) + file_name[dir_len] = DIRECTORY_SEPARATOR; + memcpy (file_name + dir_len + add_slash, base, base_len + 1); + } + } + + if (file_name == NULL || (fp = fopen (file_name, "r")) == NULL) + /* Out of memory or file not found, treat it as empty. */ + cp = ""; + else + { + /* Parse the file's contents. */ + char *res_ptr = NULL; + size_t res_size = 0; + + for (;;) + { + int c; + char buf1[50+1]; + char buf2[50+1]; + size_t l1, l2; + char *old_res_ptr; + + c = getc (fp); + if (c == EOF) + break; + if (c == '\n' || c == ' ' || c == '\t') + continue; + if (c == '#') + { + /* Skip comment, to end of line. */ + do + c = getc (fp); + while (!(c == EOF || c == '\n')); + if (c == EOF) + break; + continue; + } + ungetc (c, fp); + if (fscanf (fp, "%50s %50s", buf1, buf2) < 2) + break; + l1 = strlen (buf1); + l2 = strlen (buf2); + old_res_ptr = res_ptr; + if (res_size == 0) + { + res_size = l1 + 1 + l2 + 1; + res_ptr = (char *) malloc (res_size + 1); + } + else + { + res_size += l1 + 1 + l2 + 1; + res_ptr = (char *) realloc (res_ptr, res_size + 1); + } + if (res_ptr == NULL) + { + /* Out of memory. */ + res_size = 0; + if (old_res_ptr != NULL) + free (old_res_ptr); + break; + } + strcpy (res_ptr + res_size - (l2 + 1) - (l1 + 1), buf1); + strcpy (res_ptr + res_size - (l2 + 1), buf2); + } + fclose (fp); + if (res_size == 0) + cp = ""; + else + { + *(res_ptr + res_size) = '\0'; + cp = res_ptr; + } + } + + if (file_name != NULL) + free (file_name); + +#else + +# if defined VMS + /* To avoid the troubles of an extra file charset.alias_vms in the + sources of many GNU packages, simply inline the aliases here. */ + /* The list of encodings is taken from the OpenVMS 7.3-1 documentation + "Compaq C Run-Time Library Reference Manual for OpenVMS systems" + section 10.7 "Handling Different Character Sets". */ + cp = "ISO8859-1" "\0" "ISO-8859-1" "\0" + "ISO8859-2" "\0" "ISO-8859-2" "\0" + "ISO8859-5" "\0" "ISO-8859-5" "\0" + "ISO8859-7" "\0" "ISO-8859-7" "\0" + "ISO8859-8" "\0" "ISO-8859-8" "\0" + "ISO8859-9" "\0" "ISO-8859-9" "\0" + /* Japanese */ + "eucJP" "\0" "EUC-JP" "\0" + "SJIS" "\0" "SHIFT_JIS" "\0" + "DECKANJI" "\0" "DEC-KANJI" "\0" + "SDECKANJI" "\0" "EUC-JP" "\0" + /* Chinese */ + "eucTW" "\0" "EUC-TW" "\0" + "DECHANYU" "\0" "DEC-HANYU" "\0" + "DECHANZI" "\0" "GB2312" "\0" + /* Korean */ + "DECKOREAN" "\0" "EUC-KR" "\0"; +# endif + +# if defined WIN32_NATIVE || defined __CYGWIN__ + /* To avoid the troubles of installing a separate file in the same + directory as the DLL and of retrieving the DLL's directory at + runtime, simply inline the aliases here. */ + + cp = "CP936" "\0" "GBK" "\0" + "CP1361" "\0" "JOHAB" "\0" + "CP20127" "\0" "ASCII" "\0" + "CP20866" "\0" "KOI8-R" "\0" + "CP20936" "\0" "GB2312" "\0" + "CP21866" "\0" "KOI8-RU" "\0" + "CP28591" "\0" "ISO-8859-1" "\0" + "CP28592" "\0" "ISO-8859-2" "\0" + "CP28593" "\0" "ISO-8859-3" "\0" + "CP28594" "\0" "ISO-8859-4" "\0" + "CP28595" "\0" "ISO-8859-5" "\0" + "CP28596" "\0" "ISO-8859-6" "\0" + "CP28597" "\0" "ISO-8859-7" "\0" + "CP28598" "\0" "ISO-8859-8" "\0" + "CP28599" "\0" "ISO-8859-9" "\0" + "CP28605" "\0" "ISO-8859-15" "\0" + "CP38598" "\0" "ISO-8859-8" "\0" + "CP51932" "\0" "EUC-JP" "\0" + "CP51936" "\0" "GB2312" "\0" + "CP51949" "\0" "EUC-KR" "\0" + "CP51950" "\0" "EUC-TW" "\0" + "CP54936" "\0" "GB18030" "\0" + "CP65001" "\0" "UTF-8" "\0"; +# endif +#endif + + charset_aliases = cp; + } + + return cp; +} + +/* Determine the current locale's character encoding, and canonicalize it + into one of the canonical names listed in config.charset. + The result must not be freed; it is statically allocated. + If the canonical name cannot be determined, the result is a non-canonical + name. */ + +#ifdef STATIC +STATIC +#endif +const char * +locale_charset (void) +{ + const char *codeset; + const char *aliases; + +#if !(defined WIN32_NATIVE || defined OS2) + +# if HAVE_LANGINFO_CODESET + + /* Most systems support nl_langinfo (CODESET) nowadays. */ + codeset = nl_langinfo (CODESET); + +# ifdef __CYGWIN__ + /* Cygwin 2006 does not have locales. nl_langinfo (CODESET) always + returns "US-ASCII". As long as this is not fixed, return the suffix + of the locale name from the environment variables (if present) or + the codepage as a number. */ + if (codeset != NULL && strcmp (codeset, "US-ASCII") == 0) + { + const char *locale; + static char buf[2 + 10 + 1]; + + locale = getenv ("LC_ALL"); + if (locale == NULL || locale[0] == '\0') + { + locale = getenv ("LC_CTYPE"); + if (locale == NULL || locale[0] == '\0') + locale = getenv ("LANG"); + } + if (locale != NULL && locale[0] != '\0') + { + /* If the locale name contains an encoding after the dot, return + it. */ + const char *dot = strchr (locale, '.'); + + if (dot != NULL) + { + const char *modifier; + + dot++; + /* Look for the possible @... trailer and remove it, if any. */ + modifier = strchr (dot, '@'); + if (modifier == NULL) + return dot; + if (modifier - dot < sizeof (buf)) + { + memcpy (buf, dot, modifier - dot); + buf [modifier - dot] = '\0'; + return buf; + } + } + } + + /* Woe32 has a function returning the locale's codepage as a number. */ + sprintf (buf, "CP%u", GetACP ()); + codeset = buf; + } +# endif + +# else + + /* On old systems which lack it, use setlocale or getenv. */ + const char *locale = NULL; + + /* But most old systems don't have a complete set of locales. Some + (like SunOS 4 or DJGPP) have only the C locale. Therefore we don't + use setlocale here; it would return "C" when it doesn't support the + locale name the user has set. */ +# if 0 + locale = setlocale (LC_CTYPE, NULL); +# endif + if (locale == NULL || locale[0] == '\0') + { + locale = getenv ("LC_ALL"); + if (locale == NULL || locale[0] == '\0') + { + locale = getenv ("LC_CTYPE"); + if (locale == NULL || locale[0] == '\0') + locale = getenv ("LANG"); + } + } + + /* On some old systems, one used to set locale = "iso8859_1". On others, + you set it to "language_COUNTRY.charset". In any case, we resolve it + through the charset.alias file. */ + codeset = locale; + +# endif + +#elif defined WIN32_NATIVE + + static char buf[2 + 10 + 1]; + + /* Woe32 has a function returning the locale's codepage as a number. */ + sprintf (buf, "CP%u", GetACP ()); + codeset = buf; + +#elif defined OS2 + + const char *locale; + static char buf[2 + 10 + 1]; + ULONG cp[3]; + ULONG cplen; + + /* Allow user to override the codeset, as set in the operating system, + with standard language environment variables. */ + locale = getenv ("LC_ALL"); + if (locale == NULL || locale[0] == '\0') + { + locale = getenv ("LC_CTYPE"); + if (locale == NULL || locale[0] == '\0') + locale = getenv ("LANG"); + } + if (locale != NULL && locale[0] != '\0') + { + /* If the locale name contains an encoding after the dot, return it. */ + const char *dot = strchr (locale, '.'); + + if (dot != NULL) + { + const char *modifier; + + dot++; + /* Look for the possible @... trailer and remove it, if any. */ + modifier = strchr (dot, '@'); + if (modifier == NULL) + return dot; + if (modifier - dot < sizeof (buf)) + { + memcpy (buf, dot, modifier - dot); + buf [modifier - dot] = '\0'; + return buf; + } + } + + /* Resolve through the charset.alias file. */ + codeset = locale; + } + else + { + /* OS/2 has a function returning the locale's codepage as a number. */ + if (DosQueryCp (sizeof (cp), cp, &cplen)) + codeset = ""; + else + { + sprintf (buf, "CP%u", cp[0]); + codeset = buf; + } + } + +#endif + + if (codeset == NULL) + /* The canonical name cannot be determined. */ + codeset = ""; + + /* Resolve alias. */ + for (aliases = get_charset_aliases (); + *aliases != '\0'; + aliases += strlen (aliases) + 1, aliases += strlen (aliases) + 1) + if (strcmp (codeset, aliases) == 0 + || (aliases[0] == '*' && aliases[1] == '\0')) + { + codeset = aliases + strlen (aliases) + 1; + break; + } + + /* Don't return an empty string. GNU libc and GNU libiconv interpret + the empty string as denoting "the locale's character encoding", + thus GNU libiconv would call this function a second time. */ + if (codeset[0] == '\0') + codeset = "ASCII"; + + return codeset; +} diff --git a/src/bin/findutils/gnulib/lib/localcharset.h b/src/bin/findutils/gnulib/lib/localcharset.h new file mode 100644 index 0000000000..b9a3013ae3 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/localcharset.h @@ -0,0 +1,41 @@ +/* Determine a canonical name for the current locale's character encoding. + Copyright (C) 2000-2003 Free Software Foundation, Inc. + This file is part of the GNU CHARSET Library. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _LOCALCHARSET_H +#define _LOCALCHARSET_H + + +#ifdef __cplusplus +extern "C" { +#endif + + +/* Determine the current locale's character encoding, and canonicalize it + into one of the canonical names listed in config.charset. + The result must not be freed; it is statically allocated. + If the canonical name cannot be determined, the result is a non-canonical + name. */ +extern const char * locale_charset (void); + + +#ifdef __cplusplus +} +#endif + + +#endif /* _LOCALCHARSET_H */ diff --git a/src/bin/findutils/gnulib/lib/lseek.c b/src/bin/findutils/gnulib/lib/lseek.c new file mode 100644 index 0000000000..f2ed8bb54c --- /dev/null +++ b/src/bin/findutils/gnulib/lib/lseek.c @@ -0,0 +1,62 @@ +/* An lseek() function that detects pipes. + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#include + +/* Specification. */ +#include + +#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ +/* Windows platforms. */ +/* Get GetFileType. */ +# include +#else +# include +#endif +#include + +#undef lseek + +off_t +rpl_lseek (int fd, off_t offset, int whence) +{ +#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ + /* mingw lseek mistakenly succeeds on pipes, sockets, and terminals. */ + HANDLE h = (HANDLE) _get_osfhandle (fd); + if (h == INVALID_HANDLE_VALUE) + { + errno = EBADF; + return -1; + } + if (GetFileType (h) != FILE_TYPE_DISK) + { + errno = ESPIPE; + return -1; + } +#else + /* BeOS lseek mistakenly succeeds on pipes... */ + struct stat statbuf; + if (fstat (fd, &statbuf) < 0) + return -1; + if (!S_ISREG (statbuf.st_mode)) + { + errno = ESPIPE; + return -1; + } +#endif + return lseek (fd, offset, whence); +} diff --git a/src/bin/findutils/gnulib/lib/lstat.c b/src/bin/findutils/gnulib/lib/lstat.c new file mode 100644 index 0000000000..9dcb4cdc5b --- /dev/null +++ b/src/bin/findutils/gnulib/lib/lstat.c @@ -0,0 +1,75 @@ +/* Work around a bug of lstat on some systems + + Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free + Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include + +/* The specification of these functions is in sys_stat.h. But we cannot + include this include file here, because on some systems, a + "#define lstat lstat64" is being used, and sys_stat.h deletes this + definition. */ + +#include +#include +#include +#include + +/* lstat works differently on Linux and Solaris systems. POSIX (see + `pathname resolution' in the glossary) requires that programs like + `ls' take into consideration the fact that FILE has a trailing slash + when FILE is a symbolic link. On Linux and Solaris 10 systems, the + lstat function already has the desired semantics (in treating + `lstat ("symlink/", sbuf)' just like `lstat ("symlink/.", sbuf)', + but on Solaris 9 and earlier it does not. + + If FILE has a trailing slash and specifies a symbolic link, + then use stat() to get more info on the referent of FILE. + If the referent is a non-directory, then set errno to ENOTDIR + and return -1. Otherwise, return stat's result. */ + +int +rpl_lstat (const char *file, struct stat *sbuf) +{ + size_t len; + int lstat_result = lstat (file, sbuf); + + if (lstat_result != 0 || !S_ISLNK (sbuf->st_mode)) + return lstat_result; + + len = strlen (file); + if (len == 0 || file[len - 1] != '/') + return 0; + + /* FILE refers to a symbolic link and the name ends with a slash. + Call stat() to get info about the link's referent. */ + + /* If stat fails, then we do the same. */ + if (stat (file, sbuf) != 0) + return -1; + + /* If FILE references a directory, return 0. */ + if (S_ISDIR (sbuf->st_mode)) + return 0; + + /* Here, we know stat succeeded and FILE references a non-directory. + But it was specified via a name including a trailing slash. + Fail with errno set to ENOTDIR to indicate the contradiction. */ + errno = ENOTDIR; + return -1; +} diff --git a/src/bin/findutils/gnulib/lib/lstat.h b/src/bin/findutils/gnulib/lib/lstat.h new file mode 100644 index 0000000000..63b21c89c1 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/lstat.h @@ -0,0 +1,23 @@ +/* Retrieving information about files. + Copyright (C) 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#if !LSTAT_FOLLOWS_SLASHED_SYMLINK +extern int rpl_lstat (const char *name, struct stat *buf); +# undef lstat +# define lstat rpl_lstat +#endif diff --git a/src/bin/findutils/gnulib/lib/malloc.c b/src/bin/findutils/gnulib/lib/malloc.c new file mode 100644 index 0000000000..f2f6663790 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/malloc.c @@ -0,0 +1,57 @@ +/* malloc() function that is glibc compatible. + + Copyright (C) 1997, 1998, 2006, 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* written by Jim Meyering and Bruno Haible */ + +#include +/* Only the AC_FUNC_MALLOC macro defines 'malloc' already in config.h. */ +#ifdef malloc +# define NEED_MALLOC_GNU +# undef malloc +#endif + +/* Specification. */ +#include + +#include + +/* Call the system's malloc below. */ +#undef malloc + +/* Allocate an N-byte block of memory from the heap. + If N is zero, allocate a 1-byte block. */ + +void * +rpl_malloc (size_t n) +{ + void *result; + +#ifdef NEED_MALLOC_GNU + if (n == 0) + n = 1; +#endif + + result = malloc (n); + +#if !HAVE_MALLOC_POSIX + if (result == NULL) + errno = ENOMEM; +#endif + + return result; +} diff --git a/src/bin/findutils/gnulib/lib/malloca.c b/src/bin/findutils/gnulib/lib/malloca.c new file mode 100644 index 0000000000..1f410781db --- /dev/null +++ b/src/bin/findutils/gnulib/lib/malloca.c @@ -0,0 +1,137 @@ +/* Safe automatic memory allocation. + Copyright (C) 2003, 2006-2007 Free Software Foundation, Inc. + Written by Bruno Haible , 2003. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#include + +/* Specification. */ +#include "malloca.h" + +/* The speed critical point in this file is freea() applied to an alloca() + result: it must be fast, to match the speed of alloca(). The speed of + mmalloca() and freea() in the other case are not critical, because they + are only invoked for big memory sizes. */ + +#if HAVE_ALLOCA + +/* Store the mmalloca() results in a hash table. This is needed to reliably + distinguish a mmalloca() result and an alloca() result. + + Although it is possible that the same pointer is returned by alloca() and + by mmalloca() at different times in the same application, it does not lead + to a bug in freea(), because: + - Before a pointer returned by alloca() can point into malloc()ed memory, + the function must return, and once this has happened the programmer must + not call freea() on it anyway. + - Before a pointer returned by mmalloca() can point into the stack, it + must be freed. The only function that can free it is freea(), and + when freea() frees it, it also removes it from the hash table. */ + +#define MAGIC_NUMBER 0x1415fb4a +#define MAGIC_SIZE sizeof (int) +/* This is how the header info would look like without any alignment + considerations. */ +struct preliminary_header { void *next; char room[MAGIC_SIZE]; }; +/* But the header's size must be a multiple of sa_alignment_max. */ +#define HEADER_SIZE \ + (((sizeof (struct preliminary_header) + sa_alignment_max - 1) / sa_alignment_max) * sa_alignment_max) +struct header { void *next; char room[HEADER_SIZE - sizeof (struct preliminary_header) + MAGIC_SIZE]; }; +/* Verify that HEADER_SIZE == sizeof (struct header). */ +typedef int verify1[2 * (HEADER_SIZE == sizeof (struct header)) - 1]; +/* We make the hash table quite big, so that during lookups the probability + of empty hash buckets is quite high. There is no need to make the hash + table resizable, because when the hash table gets filled so much that the + lookup becomes slow, it means that the application has memory leaks. */ +#define HASH_TABLE_SIZE 257 +static void * mmalloca_results[HASH_TABLE_SIZE]; + +#endif + +void * +mmalloca (size_t n) +{ +#if HAVE_ALLOCA + /* Allocate one more word, that serves as an indicator for malloc()ed + memory, so that freea() of an alloca() result is fast. */ + size_t nplus = n + HEADER_SIZE; + + if (nplus >= n) + { + char *p = (char *) malloc (nplus); + + if (p != NULL) + { + size_t slot; + + p += HEADER_SIZE; + + /* Put a magic number into the indicator word. */ + ((int *) p)[-1] = MAGIC_NUMBER; + + /* Enter p into the hash table. */ + slot = (unsigned long) p % HASH_TABLE_SIZE; + ((struct header *) (p - HEADER_SIZE))->next = mmalloca_results[slot]; + mmalloca_results[slot] = p; + + return p; + } + } + /* Out of memory. */ + return NULL; +#else +# if !MALLOC_0_IS_NONNULL + if (n == 0) + n = 1; +# endif + return malloc (n); +#endif +} + +#if HAVE_ALLOCA +void +freea (void *p) +{ + /* mmalloca() may have returned NULL. */ + if (p != NULL) + { + /* Attempt to quickly distinguish the mmalloca() result - which has + a magic indicator word - and the alloca() result - which has an + uninitialized indicator word. It is for this test that sa_increment + additional bytes are allocated in the alloca() case. */ + if (((int *) p)[-1] == MAGIC_NUMBER) + { + /* Looks like a mmalloca() result. To see whether it really is one, + perform a lookup in the hash table. */ + size_t slot = (unsigned long) p % HASH_TABLE_SIZE; + void **chain = &mmalloca_results[slot]; + for (; *chain != NULL;) + { + if (*chain == p) + { + /* Found it. Remove it from the hash table and free it. */ + char *p_begin = (char *) p - HEADER_SIZE; + *chain = ((struct header *) p_begin)->next; + free (p_begin); + return; + } + chain = &((struct header *) ((char *) *chain - HEADER_SIZE))->next; + } + } + /* At this point, we know it was not a mmalloca() result. */ + } +} +#endif diff --git a/src/bin/findutils/gnulib/lib/malloca.h b/src/bin/findutils/gnulib/lib/malloca.h new file mode 100644 index 0000000000..c3c9576db3 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/malloca.h @@ -0,0 +1,124 @@ +/* Safe automatic memory allocation. + Copyright (C) 2003-2007 Free Software Foundation, Inc. + Written by Bruno Haible , 2003. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _MALLOCA_H +#define _MALLOCA_H + +#include +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +/* safe_alloca(N) is equivalent to alloca(N) when it is safe to call + alloca(N); otherwise it returns NULL. It either returns N bytes of + memory allocated on the stack, that lasts until the function returns, + or NULL. + Use of safe_alloca should be avoided: + - inside arguments of function calls - undefined behaviour, + - in inline functions - the allocation may actually last until the + calling function returns. +*/ +#if HAVE_ALLOCA +/* The OS usually guarantees only one guard page at the bottom of the stack, + and a page size can be as small as 4096 bytes. So we cannot safely + allocate anything larger than 4096 bytes. Also care for the possibility + of a few compiler-allocated temporary stack slots. + This must be a macro, not an inline function. */ +# define safe_alloca(N) ((N) < 4032 ? alloca (N) : NULL) +#else +# define safe_alloca(N) ((void) (N), NULL) +#endif + +/* malloca(N) is a safe variant of alloca(N). It allocates N bytes of + memory allocated on the stack, that must be freed using freea() before + the function returns. Upon failure, it returns NULL. */ +#if HAVE_ALLOCA +# define malloca(N) \ + ((N) < 4032 - sa_increment \ + ? (void *) ((char *) alloca ((N) + sa_increment) + sa_increment) \ + : mmalloca (N)) +#else +# define malloca(N) \ + mmalloca (N) +#endif +extern void * mmalloca (size_t n); + +/* Free a block of memory allocated through malloca(). */ +#if HAVE_ALLOCA +extern void freea (void *p); +#else +# define freea free +#endif + +/* Maybe we should also define a variant + nmalloca (size_t n, size_t s) - behaves like malloca (n * s) + If this would be useful in your application. please speak up. */ + + +#ifdef __cplusplus +} +#endif + + +/* ------------------- Auxiliary, non-public definitions ------------------- */ + +/* Determine the alignment of a type at compile time. */ +#if defined __GNUC__ +# define sa_alignof __alignof__ +#elif defined __cplusplus + template struct sa_alignof_helper { char __slot1; type __slot2; }; +# define sa_alignof(type) offsetof (sa_alignof_helper, __slot2) +#elif defined __hpux + /* Work around a HP-UX 10.20 cc bug with enums constants defined as offsetof + values. */ +# define sa_alignof(type) (sizeof (type) <= 4 ? 4 : 8) +#elif defined _AIX + /* Work around an AIX 3.2.5 xlc bug with enums constants defined as offsetof + values. */ +# define sa_alignof(type) (sizeof (type) <= 4 ? 4 : 8) +#else +# define sa_alignof(type) offsetof (struct { char __slot1; type __slot2; }, __slot2) +#endif + +enum +{ +/* The desired alignment of memory allocations is the maximum alignment + among all elementary types. */ + sa_alignment_long = sa_alignof (long), + sa_alignment_double = sa_alignof (double), +#if HAVE_LONG_LONG_INT + sa_alignment_longlong = sa_alignof (long long), +#endif + sa_alignment_longdouble = sa_alignof (long double), + sa_alignment_max = ((sa_alignment_long - 1) | (sa_alignment_double - 1) +#if HAVE_LONG_LONG_INT + | (sa_alignment_longlong - 1) +#endif + | (sa_alignment_longdouble - 1) + ) + 1, +/* The increment that guarantees room for a magic word must be >= sizeof (int) + and a multiple of sa_alignment_max. */ + sa_increment = ((sizeof (int) + sa_alignment_max - 1) / sa_alignment_max) * sa_alignment_max +}; + +#endif /* _MALLOCA_H */ diff --git a/src/bin/findutils/gnulib/lib/memcmp.c b/src/bin/findutils/gnulib/lib/memcmp.c new file mode 100644 index 0000000000..78735f5e38 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/memcmp.c @@ -0,0 +1,361 @@ +/* Copyright (C) 1991, 1993, 1995, 1997, 1998, 2003, 2006 Free Software + Foundation, Inc. + + Contributed by Torbjorn Granlund (tege@sics.se). + + NOTE: The canonical source of this file is maintained with the GNU C Library. + Bugs can be reported to bug-glibc@prep.ai.mit.edu. + + This program is free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation; either version 3 of the License, or any + later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef _LIBC +# include +#endif + +#include + +#undef memcmp + +#ifdef _LIBC + +# include +# include + +# if __BYTE_ORDER == __BIG_ENDIAN +# define WORDS_BIGENDIAN +# endif + +#else /* Not in the GNU C library. */ + +# include + +/* Type to use for aligned memory operations. + This should normally be the biggest type supported by a single load + and store. Must be an unsigned type. */ +# define op_t unsigned long int +# define OPSIZ (sizeof(op_t)) + +/* Threshold value for when to enter the unrolled loops. */ +# define OP_T_THRES 16 + +/* Type to use for unaligned operations. */ +typedef unsigned char byte; + +# ifndef WORDS_BIGENDIAN +# define MERGE(w0, sh_1, w1, sh_2) (((w0) >> (sh_1)) | ((w1) << (sh_2))) +# else +# define MERGE(w0, sh_1, w1, sh_2) (((w0) << (sh_1)) | ((w1) >> (sh_2))) +# endif + +#endif /* In the GNU C library. */ + +#ifdef WORDS_BIGENDIAN +# define CMP_LT_OR_GT(a, b) ((a) > (b) ? 1 : -1) +#else +# define CMP_LT_OR_GT(a, b) memcmp_bytes ((a), (b)) +#endif + +/* BE VERY CAREFUL IF YOU CHANGE THIS CODE! */ + +/* The strategy of this memcmp is: + + 1. Compare bytes until one of the block pointers is aligned. + + 2. Compare using memcmp_common_alignment or + memcmp_not_common_alignment, regarding the alignment of the other + block after the initial byte operations. The maximum number of + full words (of type op_t) are compared in this way. + + 3. Compare the few remaining bytes. */ + +#ifndef WORDS_BIGENDIAN +/* memcmp_bytes -- Compare A and B bytewise in the byte order of the machine. + A and B are known to be different. + This is needed only on little-endian machines. */ + +# ifdef __GNUC__ +__inline +# endif +static int +memcmp_bytes (long unsigned int a, long unsigned int b) +{ + long int srcp1 = (long int) &a; + long int srcp2 = (long int) &b; + op_t a0, b0; + + do + { + a0 = ((byte *) srcp1)[0]; + b0 = ((byte *) srcp2)[0]; + srcp1 += 1; + srcp2 += 1; + } + while (a0 == b0); + return a0 - b0; +} +#endif + +/* memcmp_common_alignment -- Compare blocks at SRCP1 and SRCP2 with LEN `op_t' + objects (not LEN bytes!). Both SRCP1 and SRCP2 should be aligned for + memory operations on `op_t's. */ +#ifdef __GNUC__ +__inline +#endif +static int +memcmp_common_alignment (long int srcp1, long int srcp2, size_t len) +{ + op_t a0, a1; + op_t b0, b1; + + switch (len % 4) + { + default: /* Avoid warning about uninitialized local variables. */ + case 2: + a0 = ((op_t *) srcp1)[0]; + b0 = ((op_t *) srcp2)[0]; + srcp1 -= 2 * OPSIZ; + srcp2 -= 2 * OPSIZ; + len += 2; + goto do1; + case 3: + a1 = ((op_t *) srcp1)[0]; + b1 = ((op_t *) srcp2)[0]; + srcp1 -= OPSIZ; + srcp2 -= OPSIZ; + len += 1; + goto do2; + case 0: + if (OP_T_THRES <= 3 * OPSIZ && len == 0) + return 0; + a0 = ((op_t *) srcp1)[0]; + b0 = ((op_t *) srcp2)[0]; + goto do3; + case 1: + a1 = ((op_t *) srcp1)[0]; + b1 = ((op_t *) srcp2)[0]; + srcp1 += OPSIZ; + srcp2 += OPSIZ; + len -= 1; + if (OP_T_THRES <= 3 * OPSIZ && len == 0) + goto do0; + /* Fall through. */ + } + + do + { + a0 = ((op_t *) srcp1)[0]; + b0 = ((op_t *) srcp2)[0]; + if (a1 != b1) + return CMP_LT_OR_GT (a1, b1); + + do3: + a1 = ((op_t *) srcp1)[1]; + b1 = ((op_t *) srcp2)[1]; + if (a0 != b0) + return CMP_LT_OR_GT (a0, b0); + + do2: + a0 = ((op_t *) srcp1)[2]; + b0 = ((op_t *) srcp2)[2]; + if (a1 != b1) + return CMP_LT_OR_GT (a1, b1); + + do1: + a1 = ((op_t *) srcp1)[3]; + b1 = ((op_t *) srcp2)[3]; + if (a0 != b0) + return CMP_LT_OR_GT (a0, b0); + + srcp1 += 4 * OPSIZ; + srcp2 += 4 * OPSIZ; + len -= 4; + } + while (len != 0); + + /* This is the right position for do0. Please don't move + it into the loop. */ + do0: + if (a1 != b1) + return CMP_LT_OR_GT (a1, b1); + return 0; +} + +/* memcmp_not_common_alignment -- Compare blocks at SRCP1 and SRCP2 with LEN + `op_t' objects (not LEN bytes!). SRCP2 should be aligned for memory + operations on `op_t', but SRCP1 *should be unaligned*. */ +#ifdef __GNUC__ +__inline +#endif +static int +memcmp_not_common_alignment (long int srcp1, long int srcp2, size_t len) +{ + op_t a0, a1, a2, a3; + op_t b0, b1, b2, b3; + op_t x; + int shl, shr; + + /* Calculate how to shift a word read at the memory operation + aligned srcp1 to make it aligned for comparison. */ + + shl = 8 * (srcp1 % OPSIZ); + shr = 8 * OPSIZ - shl; + + /* Make SRCP1 aligned by rounding it down to the beginning of the `op_t' + it points in the middle of. */ + srcp1 &= -OPSIZ; + + switch (len % 4) + { + default: /* Avoid warning about uninitialized local variables. */ + case 2: + a1 = ((op_t *) srcp1)[0]; + a2 = ((op_t *) srcp1)[1]; + b2 = ((op_t *) srcp2)[0]; + srcp1 -= 1 * OPSIZ; + srcp2 -= 2 * OPSIZ; + len += 2; + goto do1; + case 3: + a0 = ((op_t *) srcp1)[0]; + a1 = ((op_t *) srcp1)[1]; + b1 = ((op_t *) srcp2)[0]; + srcp2 -= 1 * OPSIZ; + len += 1; + goto do2; + case 0: + if (OP_T_THRES <= 3 * OPSIZ && len == 0) + return 0; + a3 = ((op_t *) srcp1)[0]; + a0 = ((op_t *) srcp1)[1]; + b0 = ((op_t *) srcp2)[0]; + srcp1 += 1 * OPSIZ; + goto do3; + case 1: + a2 = ((op_t *) srcp1)[0]; + a3 = ((op_t *) srcp1)[1]; + b3 = ((op_t *) srcp2)[0]; + srcp1 += 2 * OPSIZ; + srcp2 += 1 * OPSIZ; + len -= 1; + if (OP_T_THRES <= 3 * OPSIZ && len == 0) + goto do0; + /* Fall through. */ + } + + do + { + a0 = ((op_t *) srcp1)[0]; + b0 = ((op_t *) srcp2)[0]; + x = MERGE(a2, shl, a3, shr); + if (x != b3) + return CMP_LT_OR_GT (x, b3); + + do3: + a1 = ((op_t *) srcp1)[1]; + b1 = ((op_t *) srcp2)[1]; + x = MERGE(a3, shl, a0, shr); + if (x != b0) + return CMP_LT_OR_GT (x, b0); + + do2: + a2 = ((op_t *) srcp1)[2]; + b2 = ((op_t *) srcp2)[2]; + x = MERGE(a0, shl, a1, shr); + if (x != b1) + return CMP_LT_OR_GT (x, b1); + + do1: + a3 = ((op_t *) srcp1)[3]; + b3 = ((op_t *) srcp2)[3]; + x = MERGE(a1, shl, a2, shr); + if (x != b2) + return CMP_LT_OR_GT (x, b2); + + srcp1 += 4 * OPSIZ; + srcp2 += 4 * OPSIZ; + len -= 4; + } + while (len != 0); + + /* This is the right position for do0. Please don't move + it into the loop. */ + do0: + x = MERGE(a2, shl, a3, shr); + if (x != b3) + return CMP_LT_OR_GT (x, b3); + return 0; +} + +int +rpl_memcmp (const void *s1, const void *s2, size_t len) +{ + op_t a0; + op_t b0; + long int srcp1 = (long int) s1; + long int srcp2 = (long int) s2; + op_t res; + + if (len >= OP_T_THRES) + { + /* There are at least some bytes to compare. No need to test + for LEN == 0 in this alignment loop. */ + while (srcp2 % OPSIZ != 0) + { + a0 = ((byte *) srcp1)[0]; + b0 = ((byte *) srcp2)[0]; + srcp1 += 1; + srcp2 += 1; + res = a0 - b0; + if (res != 0) + return res; + len -= 1; + } + + /* SRCP2 is now aligned for memory operations on `op_t'. + SRCP1 alignment determines if we can do a simple, + aligned compare or need to shuffle bits. */ + + if (srcp1 % OPSIZ == 0) + res = memcmp_common_alignment (srcp1, srcp2, len / OPSIZ); + else + res = memcmp_not_common_alignment (srcp1, srcp2, len / OPSIZ); + if (res != 0) + return res; + + /* Number of bytes remaining in the interval [0..OPSIZ-1]. */ + srcp1 += len & -OPSIZ; + srcp2 += len & -OPSIZ; + len %= OPSIZ; + } + + /* There are just a few bytes to compare. Use byte memory operations. */ + while (len != 0) + { + a0 = ((byte *) srcp1)[0]; + b0 = ((byte *) srcp2)[0]; + srcp1 += 1; + srcp2 += 1; + res = a0 - b0; + if (res != 0) + return res; + len -= 1; + } + + return 0; +} + +#ifdef weak_alias +# undef bcmp +weak_alias (memcmp, bcmp) +#endif diff --git a/src/bin/findutils/gnulib/lib/mempcpy.c b/src/bin/findutils/gnulib/lib/mempcpy.c new file mode 100644 index 0000000000..33c7a607e2 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/mempcpy.c @@ -0,0 +1,29 @@ +/* Copy memory area and return pointer after last written byte. + Copyright (C) 2003, 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#include + +/* Specification. */ +#include + +/* Copy N bytes of SRC to DEST, return pointer to bytes after the + last written byte. */ +void * +mempcpy (void *dest, const void *src, size_t n) +{ + return (char *) memcpy (dest, src, n) + n; +} diff --git a/src/bin/findutils/gnulib/lib/memrchr.c b/src/bin/findutils/gnulib/lib/memrchr.c new file mode 100644 index 0000000000..50b27c0291 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/memrchr.c @@ -0,0 +1,189 @@ +/* memrchr -- find the last occurrence of a byte in a memory block + + Copyright (C) 1991, 1993, 1996, 1997, 1999, 2000, 2003, 2004, 2005, + 2006, 2007 Free Software Foundation, Inc. + + Based on strlen implementation by Torbjorn Granlund (tege@sics.se), + with help from Dan Sahlin (dan@sics.se) and + commentary by Jim Blandy (jimb@ai.mit.edu); + adaptation to memchr suggested by Dick Karpinski (dick@cca.ucsf.edu), + and implemented by Roland McGrath (roland@ai.mit.edu). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#if defined _LIBC +# include +#else +# include +# define reg_char char +#endif + +#include +#include + +#undef __memrchr +#undef memrchr + +#ifndef weak_alias +# define __memrchr memrchr +#endif + +/* Search no more than N bytes of S for C. */ +void * +__memrchr (void const *s, int c_in, size_t n) +{ + const unsigned char *char_ptr; + const unsigned long int *longword_ptr; + unsigned long int longword, magic_bits, charmask; + unsigned reg_char c; + int i; + + c = (unsigned char) c_in; + + /* Handle the last few characters by reading one character at a time. + Do this until CHAR_PTR is aligned on a longword boundary. */ + for (char_ptr = (const unsigned char *) s + n; + n > 0 && (size_t) char_ptr % sizeof longword != 0; + --n) + if (*--char_ptr == c) + return (void *) char_ptr; + + /* All these elucidatory comments refer to 4-byte longwords, + but the theory applies equally well to any size longwords. */ + + longword_ptr = (const unsigned long int *) char_ptr; + + /* Bits 31, 24, 16, and 8 of this number are zero. Call these bits + the "holes." Note that there is a hole just to the left of + each byte, with an extra at the end: + + bits: 01111110 11111110 11111110 11111111 + bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD + + The 1-bits make sure that carries propagate to the next 0-bit. + The 0-bits provide holes for carries to fall into. */ + + /* Set MAGIC_BITS to be this pattern of 1 and 0 bits. + Set CHARMASK to be a longword, each of whose bytes is C. */ + + magic_bits = 0xfefefefe; + charmask = c | (c << 8); + charmask |= charmask << 16; +#if 0xffffffffU < ULONG_MAX + magic_bits |= magic_bits << 32; + charmask |= charmask << 32; + if (8 < sizeof longword) + for (i = 64; i < sizeof longword * 8; i *= 2) + { + magic_bits |= magic_bits << i; + charmask |= charmask << i; + } +#endif + magic_bits = (ULONG_MAX >> 1) & (magic_bits | 1); + + /* Instead of the traditional loop which tests each character, + we will test a longword at a time. The tricky part is testing + if *any of the four* bytes in the longword in question are zero. */ + while (n >= sizeof longword) + { + /* We tentatively exit the loop if adding MAGIC_BITS to + LONGWORD fails to change any of the hole bits of LONGWORD. + + 1) Is this safe? Will it catch all the zero bytes? + Suppose there is a byte with all zeros. Any carry bits + propagating from its left will fall into the hole at its + least significant bit and stop. Since there will be no + carry from its most significant bit, the LSB of the + byte to the left will be unchanged, and the zero will be + detected. + + 2) Is this worthwhile? Will it ignore everything except + zero bytes? Suppose every byte of LONGWORD has a bit set + somewhere. There will be a carry into bit 8. If bit 8 + is set, this will carry into bit 16. If bit 8 is clear, + one of bits 9-15 must be set, so there will be a carry + into bit 16. Similarly, there will be a carry into bit + 24. If one of bits 24-30 is set, there will be a carry + into bit 31, so all of the hole bits will be changed. + + The one misfire occurs when bits 24-30 are clear and bit + 31 is set; in this case, the hole at bit 31 is not + changed. If we had access to the processor carry flag, + we could close this loophole by putting the fourth hole + at bit 32! + + So it ignores everything except 128's, when they're aligned + properly. + + 3) But wait! Aren't we looking for C, not zero? + Good point. So what we do is XOR LONGWORD with a longword, + each of whose bytes is C. This turns each byte that is C + into a zero. */ + + longword = *--longword_ptr ^ charmask; + + /* Add MAGIC_BITS to LONGWORD. */ + if ((((longword + magic_bits) + + /* Set those bits that were unchanged by the addition. */ + ^ ~longword) + + /* Look at only the hole bits. If any of the hole bits + are unchanged, most likely one of the bytes was a + zero. */ + & ~magic_bits) != 0) + { + /* Which of the bytes was C? If none of them were, it was + a misfire; continue the search. */ + + const unsigned char *cp = (const unsigned char *) longword_ptr; + + if (8 < sizeof longword) + for (i = sizeof longword - 1; 8 <= i; i--) + if (cp[i] == c) + return (void *) &cp[i]; + if (7 < sizeof longword && cp[7] == c) + return (void *) &cp[7]; + if (6 < sizeof longword && cp[6] == c) + return (void *) &cp[6]; + if (5 < sizeof longword && cp[5] == c) + return (void *) &cp[5]; + if (4 < sizeof longword && cp[4] == c) + return (void *) &cp[4]; + if (cp[3] == c) + return (void *) &cp[3]; + if (cp[2] == c) + return (void *) &cp[2]; + if (cp[1] == c) + return (void *) &cp[1]; + if (cp[0] == c) + return (void *) cp; + } + + n -= sizeof longword; + } + + char_ptr = (const unsigned char *) longword_ptr; + + while (n-- > 0) + { + if (*--char_ptr == c) + return (void *) char_ptr; + } + + return 0; +} +#ifdef weak_alias +weak_alias (__memrchr, memrchr) +#endif diff --git a/src/bin/findutils/lib/memset.c b/src/bin/findutils/gnulib/lib/memset.c similarity index 65% rename from src/bin/findutils/lib/memset.c rename to src/bin/findutils/gnulib/lib/memset.c index 0e819f20ee..a1618cf42c 100644 --- a/src/bin/findutils/lib/memset.c +++ b/src/bin/findutils/gnulib/lib/memset.c @@ -1,9 +1,9 @@ /* memset.c -- set an area of memory to a given value - Copyright (C) 1991 Free Software Foundation, Inc. + Copyright (C) 1991, 2003 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) + the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, @@ -12,14 +12,13 @@ GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -char * -memset (str, c, len) - char *str; - int c; - unsigned len; +#include + +void * +memset (void *str, int c, size_t len) { register char *st = str; diff --git a/src/bin/findutils/gnulib/lib/mkdirat.c b/src/bin/findutils/gnulib/lib/mkdirat.c new file mode 100644 index 0000000000..6b6278b115 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/mkdirat.c @@ -0,0 +1,42 @@ +/* fd-relative mkdir + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include + +#include "openat.h" + +#include + +#include "dirname.h" /* solely for definition of IS_ABSOLUTE_FILE_NAME */ +#include "save-cwd.h" +#include "openat-priv.h" + +/* Solaris 10 has no function like this. + Create a subdirectory, FILE, with mode MODE, in the directory + open on descriptor FD. If possible, do it without changing the + working directory. Otherwise, resort to using save_cwd/fchdir, + then mkdir/restore_cwd. If either the save_cwd or the restore_cwd + fails, then give a diagnostic and exit nonzero. */ + +#define AT_FUNC_NAME mkdirat +#define AT_FUNC_F1 mkdir +#define AT_FUNC_F2 mkdir +#define AT_FUNC_USE_F1_COND 1 +#define AT_FUNC_POST_FILE_PARAM_DECLS , mode_t mode +#define AT_FUNC_POST_FILE_ARGS , mode +#include "at-func.c" diff --git a/src/bin/findutils/gnulib/lib/mktime.c b/src/bin/findutils/gnulib/lib/mktime.c new file mode 100644 index 0000000000..1511be1831 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/mktime.c @@ -0,0 +1,663 @@ +/* Convert a `struct tm' to a time_t value. + Copyright (C) 1993-1999, 2002-2005, 2006, 2007 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Paul Eggert . + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* Define this to have a standalone program to test this implementation of + mktime. */ +/* #define DEBUG 1 */ + +#ifndef _LIBC +# include +#endif + +/* Assume that leap seconds are possible, unless told otherwise. + If the host has a `zic' command with a `-L leapsecondfilename' option, + then it supports leap seconds; otherwise it probably doesn't. */ +#ifndef LEAP_SECONDS_POSSIBLE +# define LEAP_SECONDS_POSSIBLE 1 +#endif + +#include + +#include + +#include /* For the real memcpy prototype. */ + +#if DEBUG +# include +# include +/* Make it work even if the system's libc has its own mktime routine. */ +# define mktime my_mktime +#endif /* DEBUG */ + +/* Shift A right by B bits portably, by dividing A by 2**B and + truncating towards minus infinity. A and B should be free of side + effects, and B should be in the range 0 <= B <= INT_BITS - 2, where + INT_BITS is the number of useful bits in an int. GNU code can + assume that INT_BITS is at least 32. + + ISO C99 says that A >> B is implementation-defined if A < 0. Some + implementations (e.g., UNICOS 9.0 on a Cray Y-MP EL) don't shift + right in the usual way when A < 0, so SHR falls back on division if + ordinary A >> B doesn't seem to be the usual signed shift. */ +#define SHR(a, b) \ + (-1 >> 1 == -1 \ + ? (a) >> (b) \ + : (a) / (1 << (b)) - ((a) % (1 << (b)) < 0)) + +/* The extra casts in the following macros work around compiler bugs, + e.g., in Cray C 5.0.3.0. */ + +/* True if the arithmetic type T is an integer type. bool counts as + an integer. */ +#define TYPE_IS_INTEGER(t) ((t) 1.5 == 1) + +/* True if negative values of the signed integer type T use two's + complement, ones' complement, or signed magnitude representation, + respectively. Much GNU code assumes two's complement, but some + people like to be portable to all possible C hosts. */ +#define TYPE_TWOS_COMPLEMENT(t) ((t) ~ (t) 0 == (t) -1) +#define TYPE_ONES_COMPLEMENT(t) ((t) ~ (t) 0 == 0) +#define TYPE_SIGNED_MAGNITUDE(t) ((t) ~ (t) 0 < (t) -1) + +/* True if the arithmetic type T is signed. */ +#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1)) + +/* The maximum and minimum values for the integer type T. These + macros have undefined behavior if T is signed and has padding bits. + If this is a problem for you, please let us know how to fix it for + your host. */ +#define TYPE_MINIMUM(t) \ + ((t) (! TYPE_SIGNED (t) \ + ? (t) 0 \ + : TYPE_SIGNED_MAGNITUDE (t) \ + ? ~ (t) 0 \ + : ~ (t) 0 << (sizeof (t) * CHAR_BIT - 1))) +#define TYPE_MAXIMUM(t) \ + ((t) (! TYPE_SIGNED (t) \ + ? (t) -1 \ + : ~ (~ (t) 0 << (sizeof (t) * CHAR_BIT - 1)))) + +#ifndef TIME_T_MIN +# define TIME_T_MIN TYPE_MINIMUM (time_t) +#endif +#ifndef TIME_T_MAX +# define TIME_T_MAX TYPE_MAXIMUM (time_t) +#endif +#define TIME_T_MIDPOINT (SHR (TIME_T_MIN + TIME_T_MAX, 1) + 1) + +/* Verify a requirement at compile-time (unlike assert, which is runtime). */ +#define verify(name, assertion) struct name { char a[(assertion) ? 1 : -1]; } + +verify (time_t_is_integer, TYPE_IS_INTEGER (time_t)); +verify (twos_complement_arithmetic, TYPE_TWOS_COMPLEMENT (int)); +/* The code also assumes that signed integer overflow silently wraps + around, but this assumption can't be stated without causing a + diagnostic on some hosts. */ + +#define EPOCH_YEAR 1970 +#define TM_YEAR_BASE 1900 +verify (base_year_is_a_multiple_of_100, TM_YEAR_BASE % 100 == 0); + +/* Return 1 if YEAR + TM_YEAR_BASE is a leap year. */ +static inline int +leapyear (long int year) +{ + /* Don't add YEAR to TM_YEAR_BASE, as that might overflow. + Also, work even if YEAR is negative. */ + return + ((year & 3) == 0 + && (year % 100 != 0 + || ((year / 100) & 3) == (- (TM_YEAR_BASE / 100) & 3))); +} + +/* How many days come before each month (0-12). */ +#ifndef _LIBC +static +#endif +const unsigned short int __mon_yday[2][13] = + { + /* Normal years. */ + { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, + /* Leap years. */ + { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 } + }; + + +#ifndef _LIBC +/* Portable standalone applications should supply a that + declares a POSIX-compliant localtime_r, for the benefit of older + implementations that lack localtime_r or have a nonstandard one. + See the gnulib time_r module for one way to implement this. */ +# undef __localtime_r +# define __localtime_r localtime_r +# define __mktime_internal mktime_internal +#endif + +/* Return an integer value measuring (YEAR1-YDAY1 HOUR1:MIN1:SEC1) - + (YEAR0-YDAY0 HOUR0:MIN0:SEC0) in seconds, assuming that the clocks + were not adjusted between the time stamps. + + The YEAR values uses the same numbering as TP->tm_year. Values + need not be in the usual range. However, YEAR1 must not be less + than 2 * INT_MIN or greater than 2 * INT_MAX. + + The result may overflow. It is the caller's responsibility to + detect overflow. */ + +static inline time_t +ydhms_diff (long int year1, long int yday1, int hour1, int min1, int sec1, + int year0, int yday0, int hour0, int min0, int sec0) +{ + verify (C99_integer_division, -1 / 2 == 0); + verify (long_int_year_and_yday_are_wide_enough, + INT_MAX <= LONG_MAX / 2 || TIME_T_MAX <= UINT_MAX); + + /* Compute intervening leap days correctly even if year is negative. + Take care to avoid integer overflow here. */ + int a4 = SHR (year1, 2) + SHR (TM_YEAR_BASE, 2) - ! (year1 & 3); + int b4 = SHR (year0, 2) + SHR (TM_YEAR_BASE, 2) - ! (year0 & 3); + int a100 = a4 / 25 - (a4 % 25 < 0); + int b100 = b4 / 25 - (b4 % 25 < 0); + int a400 = SHR (a100, 2); + int b400 = SHR (b100, 2); + int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400); + + /* Compute the desired time in time_t precision. Overflow might + occur here. */ + time_t tyear1 = year1; + time_t years = tyear1 - year0; + time_t days = 365 * years + yday1 - yday0 + intervening_leap_days; + time_t hours = 24 * days + hour1 - hour0; + time_t minutes = 60 * hours + min1 - min0; + time_t seconds = 60 * minutes + sec1 - sec0; + return seconds; +} + + +/* Return a time_t value corresponding to (YEAR-YDAY HOUR:MIN:SEC), + assuming that *T corresponds to *TP and that no clock adjustments + occurred between *TP and the desired time. + If TP is null, return a value not equal to *T; this avoids false matches. + If overflow occurs, yield the minimal or maximal value, except do not + yield a value equal to *T. */ +static time_t +guess_time_tm (long int year, long int yday, int hour, int min, int sec, + const time_t *t, const struct tm *tp) +{ + if (tp) + { + time_t d = ydhms_diff (year, yday, hour, min, sec, + tp->tm_year, tp->tm_yday, + tp->tm_hour, tp->tm_min, tp->tm_sec); + time_t t1 = *t + d; + if ((t1 < *t) == (TYPE_SIGNED (time_t) ? d < 0 : TIME_T_MAX / 2 < d)) + return t1; + } + + /* Overflow occurred one way or another. Return the nearest result + that is actually in range, except don't report a zero difference + if the actual difference is nonzero, as that would cause a false + match; and don't oscillate between two values, as that would + confuse the spring-forward gap detector. */ + return (*t < TIME_T_MIDPOINT + ? (*t <= TIME_T_MIN + 1 ? *t + 1 : TIME_T_MIN) + : (TIME_T_MAX - 1 <= *t ? *t - 1 : TIME_T_MAX)); +} + +/* Use CONVERT to convert *T to a broken down time in *TP. + If *T is out of range for conversion, adjust it so that + it is the nearest in-range value and then convert that. */ +static struct tm * +ranged_convert (struct tm *(*convert) (const time_t *, struct tm *), + time_t *t, struct tm *tp) +{ + struct tm *r = convert (t, tp); + + if (!r && *t) + { + time_t bad = *t; + time_t ok = 0; + + /* BAD is a known unconvertible time_t, and OK is a known good one. + Use binary search to narrow the range between BAD and OK until + they differ by 1. */ + while (bad != ok + (bad < 0 ? -1 : 1)) + { + time_t mid = *t = (bad < 0 + ? bad + ((ok - bad) >> 1) + : ok + ((bad - ok) >> 1)); + r = convert (t, tp); + if (r) + ok = mid; + else + bad = mid; + } + + if (!r && ok) + { + /* The last conversion attempt failed; + revert to the most recent successful attempt. */ + *t = ok; + r = convert (t, tp); + } + } + + return r; +} + + +/* Convert *TP to a time_t value, inverting + the monotonic and mostly-unit-linear conversion function CONVERT. + Use *OFFSET to keep track of a guess at the offset of the result, + compared to what the result would be for UTC without leap seconds. + If *OFFSET's guess is correct, only one CONVERT call is needed. + This function is external because it is used also by timegm.c. */ +time_t +__mktime_internal (struct tm *tp, + struct tm *(*convert) (const time_t *, struct tm *), + time_t *offset) +{ + time_t t, gt, t0, t1, t2; + struct tm tm; + + /* The maximum number of probes (calls to CONVERT) should be enough + to handle any combinations of time zone rule changes, solar time, + leap seconds, and oscillations around a spring-forward gap. + POSIX.1 prohibits leap seconds, but some hosts have them anyway. */ + int remaining_probes = 6; + + /* Time requested. Copy it in case CONVERT modifies *TP; this can + occur if TP is localtime's returned value and CONVERT is localtime. */ + int sec = tp->tm_sec; + int min = tp->tm_min; + int hour = tp->tm_hour; + int mday = tp->tm_mday; + int mon = tp->tm_mon; + int year_requested = tp->tm_year; + int isdst = tp->tm_isdst; + + /* 1 if the previous probe was DST. */ + int dst2; + + /* Ensure that mon is in range, and set year accordingly. */ + int mon_remainder = mon % 12; + int negative_mon_remainder = mon_remainder < 0; + int mon_years = mon / 12 - negative_mon_remainder; + long int lyear_requested = year_requested; + long int year = lyear_requested + mon_years; + + /* The other values need not be in range: + the remaining code handles minor overflows correctly, + assuming int and time_t arithmetic wraps around. + Major overflows are caught at the end. */ + + /* Calculate day of year from year, month, and day of month. + The result need not be in range. */ + int mon_yday = ((__mon_yday[leapyear (year)] + [mon_remainder + 12 * negative_mon_remainder]) + - 1); + long int lmday = mday; + long int yday = mon_yday + lmday; + + time_t guessed_offset = *offset; + + int sec_requested = sec; + + if (LEAP_SECONDS_POSSIBLE) + { + /* Handle out-of-range seconds specially, + since ydhms_tm_diff assumes every minute has 60 seconds. */ + if (sec < 0) + sec = 0; + if (59 < sec) + sec = 59; + } + + /* Invert CONVERT by probing. First assume the same offset as last + time. */ + + t0 = ydhms_diff (year, yday, hour, min, sec, + EPOCH_YEAR - TM_YEAR_BASE, 0, 0, 0, - guessed_offset); + + if (TIME_T_MAX / INT_MAX / 366 / 24 / 60 / 60 < 3) + { + /* time_t isn't large enough to rule out overflows, so check + for major overflows. A gross check suffices, since if t0 + has overflowed, it is off by a multiple of TIME_T_MAX - + TIME_T_MIN + 1. So ignore any component of the difference + that is bounded by a small value. */ + + /* Approximate log base 2 of the number of time units per + biennium. A biennium is 2 years; use this unit instead of + years to avoid integer overflow. For example, 2 average + Gregorian years are 2 * 365.2425 * 24 * 60 * 60 seconds, + which is 63113904 seconds, and rint (log2 (63113904)) is + 26. */ + int ALOG2_SECONDS_PER_BIENNIUM = 26; + int ALOG2_MINUTES_PER_BIENNIUM = 20; + int ALOG2_HOURS_PER_BIENNIUM = 14; + int ALOG2_DAYS_PER_BIENNIUM = 10; + int LOG2_YEARS_PER_BIENNIUM = 1; + + int approx_requested_biennia = + (SHR (year_requested, LOG2_YEARS_PER_BIENNIUM) + - SHR (EPOCH_YEAR - TM_YEAR_BASE, LOG2_YEARS_PER_BIENNIUM) + + SHR (mday, ALOG2_DAYS_PER_BIENNIUM) + + SHR (hour, ALOG2_HOURS_PER_BIENNIUM) + + SHR (min, ALOG2_MINUTES_PER_BIENNIUM) + + (LEAP_SECONDS_POSSIBLE + ? 0 + : SHR (sec, ALOG2_SECONDS_PER_BIENNIUM))); + + int approx_biennia = SHR (t0, ALOG2_SECONDS_PER_BIENNIUM); + int diff = approx_biennia - approx_requested_biennia; + int abs_diff = diff < 0 ? - diff : diff; + + /* IRIX 4.0.5 cc miscaculates TIME_T_MIN / 3: it erroneously + gives a positive value of 715827882. Setting a variable + first then doing math on it seems to work. + (ghazi@caip.rutgers.edu) */ + time_t time_t_max = TIME_T_MAX; + time_t time_t_min = TIME_T_MIN; + time_t overflow_threshold = + (time_t_max / 3 - time_t_min / 3) >> ALOG2_SECONDS_PER_BIENNIUM; + + if (overflow_threshold < abs_diff) + { + /* Overflow occurred. Try repairing it; this might work if + the time zone offset is enough to undo the overflow. */ + time_t repaired_t0 = -1 - t0; + approx_biennia = SHR (repaired_t0, ALOG2_SECONDS_PER_BIENNIUM); + diff = approx_biennia - approx_requested_biennia; + abs_diff = diff < 0 ? - diff : diff; + if (overflow_threshold < abs_diff) + return -1; + guessed_offset += repaired_t0 - t0; + t0 = repaired_t0; + } + } + + /* Repeatedly use the error to improve the guess. */ + + for (t = t1 = t2 = t0, dst2 = 0; + (gt = guess_time_tm (year, yday, hour, min, sec, &t, + ranged_convert (convert, &t, &tm)), + t != gt); + t1 = t2, t2 = t, t = gt, dst2 = tm.tm_isdst != 0) + if (t == t1 && t != t2 + && (tm.tm_isdst < 0 + || (isdst < 0 + ? dst2 <= (tm.tm_isdst != 0) + : (isdst != 0) != (tm.tm_isdst != 0)))) + /* We can't possibly find a match, as we are oscillating + between two values. The requested time probably falls + within a spring-forward gap of size GT - T. Follow the common + practice in this case, which is to return a time that is GT - T + away from the requested time, preferring a time whose + tm_isdst differs from the requested value. (If no tm_isdst + was requested and only one of the two values has a nonzero + tm_isdst, prefer that value.) In practice, this is more + useful than returning -1. */ + goto offset_found; + else if (--remaining_probes == 0) + return -1; + + /* We have a match. Check whether tm.tm_isdst has the requested + value, if any. */ + if (isdst != tm.tm_isdst && 0 <= isdst && 0 <= tm.tm_isdst) + { + /* tm.tm_isdst has the wrong value. Look for a neighboring + time with the right value, and use its UTC offset. + + Heuristic: probe the adjacent timestamps in both directions, + looking for the desired isdst. This should work for all real + time zone histories in the tz database. */ + + /* Distance between probes when looking for a DST boundary. In + tzdata2003a, the shortest period of DST is 601200 seconds + (e.g., America/Recife starting 2000-10-08 01:00), and the + shortest period of non-DST surrounded by DST is 694800 + seconds (Africa/Tunis starting 1943-04-17 01:00). Use the + minimum of these two values, so we don't miss these short + periods when probing. */ + int stride = 601200; + + /* The longest period of DST in tzdata2003a is 536454000 seconds + (e.g., America/Jujuy starting 1946-10-01 01:00). The longest + period of non-DST is much longer, but it makes no real sense + to search for more than a year of non-DST, so use the DST + max. */ + int duration_max = 536454000; + + /* Search in both directions, so the maximum distance is half + the duration; add the stride to avoid off-by-1 problems. */ + int delta_bound = duration_max / 2 + stride; + + int delta, direction; + + for (delta = stride; delta < delta_bound; delta += stride) + for (direction = -1; direction <= 1; direction += 2) + { + time_t ot = t + delta * direction; + if ((ot < t) == (direction < 0)) + { + struct tm otm; + ranged_convert (convert, &ot, &otm); + if (otm.tm_isdst == isdst) + { + /* We found the desired tm_isdst. + Extrapolate back to the desired time. */ + t = guess_time_tm (year, yday, hour, min, sec, &ot, &otm); + ranged_convert (convert, &t, &tm); + goto offset_found; + } + } + } + } + + offset_found: + *offset = guessed_offset + t - t0; + + if (LEAP_SECONDS_POSSIBLE && sec_requested != tm.tm_sec) + { + /* Adjust time to reflect the tm_sec requested, not the normalized value. + Also, repair any damage from a false match due to a leap second. */ + int sec_adjustment = (sec == 0 && tm.tm_sec == 60) - sec; + t1 = t + sec_requested; + t2 = t1 + sec_adjustment; + if (((t1 < t) != (sec_requested < 0)) + | ((t2 < t1) != (sec_adjustment < 0)) + | ! convert (&t2, &tm)) + return -1; + t = t2; + } + + *tp = tm; + return t; +} + + +/* FIXME: This should use a signed type wide enough to hold any UTC + offset in seconds. 'int' should be good enough for GNU code. We + can't fix this unilaterally though, as other modules invoke + __mktime_internal. */ +static time_t localtime_offset; + +/* Convert *TP to a time_t value. */ +time_t +mktime (struct tm *tp) +{ +#ifdef _LIBC + /* POSIX.1 8.1.1 requires that whenever mktime() is called, the + time zone names contained in the external variable `tzname' shall + be set as if the tzset() function had been called. */ + __tzset (); +#endif + + return __mktime_internal (tp, __localtime_r, &localtime_offset); +} + +#ifdef weak_alias +weak_alias (mktime, timelocal) +#endif + +#ifdef _LIBC +libc_hidden_def (mktime) +libc_hidden_weak (timelocal) +#endif + +#if DEBUG + +static int +not_equal_tm (const struct tm *a, const struct tm *b) +{ + return ((a->tm_sec ^ b->tm_sec) + | (a->tm_min ^ b->tm_min) + | (a->tm_hour ^ b->tm_hour) + | (a->tm_mday ^ b->tm_mday) + | (a->tm_mon ^ b->tm_mon) + | (a->tm_year ^ b->tm_year) + | (a->tm_yday ^ b->tm_yday) + | (a->tm_isdst ^ b->tm_isdst)); +} + +static void +print_tm (const struct tm *tp) +{ + if (tp) + printf ("%04d-%02d-%02d %02d:%02d:%02d yday %03d wday %d isdst %d", + tp->tm_year + TM_YEAR_BASE, tp->tm_mon + 1, tp->tm_mday, + tp->tm_hour, tp->tm_min, tp->tm_sec, + tp->tm_yday, tp->tm_wday, tp->tm_isdst); + else + printf ("0"); +} + +static int +check_result (time_t tk, struct tm tmk, time_t tl, const struct tm *lt) +{ + if (tk != tl || !lt || not_equal_tm (&tmk, lt)) + { + printf ("mktime ("); + print_tm (lt); + printf (")\nyields ("); + print_tm (&tmk); + printf (") == %ld, should be %ld\n", (long int) tk, (long int) tl); + return 1; + } + + return 0; +} + +int +main (int argc, char **argv) +{ + int status = 0; + struct tm tm, tmk, tml; + struct tm *lt; + time_t tk, tl, tl1; + char trailer; + + if ((argc == 3 || argc == 4) + && (sscanf (argv[1], "%d-%d-%d%c", + &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &trailer) + == 3) + && (sscanf (argv[2], "%d:%d:%d%c", + &tm.tm_hour, &tm.tm_min, &tm.tm_sec, &trailer) + == 3)) + { + tm.tm_year -= TM_YEAR_BASE; + tm.tm_mon--; + tm.tm_isdst = argc == 3 ? -1 : atoi (argv[3]); + tmk = tm; + tl = mktime (&tmk); + lt = localtime (&tl); + if (lt) + { + tml = *lt; + lt = &tml; + } + printf ("mktime returns %ld == ", (long int) tl); + print_tm (&tmk); + printf ("\n"); + status = check_result (tl, tmk, tl, lt); + } + else if (argc == 4 || (argc == 5 && strcmp (argv[4], "-") == 0)) + { + time_t from = atol (argv[1]); + time_t by = atol (argv[2]); + time_t to = atol (argv[3]); + + if (argc == 4) + for (tl = from; by < 0 ? to <= tl : tl <= to; tl = tl1) + { + lt = localtime (&tl); + if (lt) + { + tmk = tml = *lt; + tk = mktime (&tmk); + status |= check_result (tk, tmk, tl, &tml); + } + else + { + printf ("localtime (%ld) yields 0\n", (long int) tl); + status = 1; + } + tl1 = tl + by; + if ((tl1 < tl) != (by < 0)) + break; + } + else + for (tl = from; by < 0 ? to <= tl : tl <= to; tl = tl1) + { + /* Null benchmark. */ + lt = localtime (&tl); + if (lt) + { + tmk = tml = *lt; + tk = tl; + status |= check_result (tk, tmk, tl, &tml); + } + else + { + printf ("localtime (%ld) yields 0\n", (long int) tl); + status = 1; + } + tl1 = tl + by; + if ((tl1 < tl) != (by < 0)) + break; + } + } + else + printf ("Usage:\ +\t%s YYYY-MM-DD HH:MM:SS [ISDST] # Test given time.\n\ +\t%s FROM BY TO # Test values FROM, FROM+BY, ..., TO.\n\ +\t%s FROM BY TO - # Do not test those values (for benchmark).\n", + argv[0], argv[0], argv[0]); + + return status; +} + +#endif /* DEBUG */ + +/* +Local Variables: +compile-command: "gcc -DDEBUG -Wall -W -O -g mktime.c -o mktime" +End: +*/ diff --git a/src/bin/findutils/gnulib/lib/modechange.c b/src/bin/findutils/gnulib/lib/modechange.c new file mode 100644 index 0000000000..1296717c5f --- /dev/null +++ b/src/bin/findutils/gnulib/lib/modechange.c @@ -0,0 +1,385 @@ +/* modechange.c -- file mode manipulation + + Copyright (C) 1989, 1990, 1997, 1998, 1999, 2001, 2003, 2004, 2005, + 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by David MacKenzie */ + +/* The ASCII mode string is compiled into an array of `struct + modechange', which can then be applied to each file to be changed. + We do this instead of re-parsing the ASCII string for each file + because the compiled form requires less computation to use; when + changing the mode of many files, this probably results in a + performance gain. */ + +#include + +#include "modechange.h" +#include +#include "stat-macros.h" +#include "xalloc.h" +#include + +/* The traditional octal values corresponding to each mode bit. */ +#define SUID 04000 +#define SGID 02000 +#define SVTX 01000 +#define RUSR 00400 +#define WUSR 00200 +#define XUSR 00100 +#define RGRP 00040 +#define WGRP 00020 +#define XGRP 00010 +#define ROTH 00004 +#define WOTH 00002 +#define XOTH 00001 +#define ALLM 07777 /* all octal mode bits */ + +/* Convert OCTAL, which uses one of the traditional octal values, to + an internal mode_t value. */ +static mode_t +octal_to_mode (unsigned int octal) +{ + /* Help the compiler optimize the usual case where mode_t uses + the traditional octal representation. */ + return ((S_ISUID == SUID && S_ISGID == SGID && S_ISVTX == SVTX + && S_IRUSR == RUSR && S_IWUSR == WUSR && S_IXUSR == XUSR + && S_IRGRP == RGRP && S_IWGRP == WGRP && S_IXGRP == XGRP + && S_IROTH == ROTH && S_IWOTH == WOTH && S_IXOTH == XOTH) + ? octal + : (mode_t) ((octal & SUID ? S_ISUID : 0) + | (octal & SGID ? S_ISGID : 0) + | (octal & SVTX ? S_ISVTX : 0) + | (octal & RUSR ? S_IRUSR : 0) + | (octal & WUSR ? S_IWUSR : 0) + | (octal & XUSR ? S_IXUSR : 0) + | (octal & RGRP ? S_IRGRP : 0) + | (octal & WGRP ? S_IWGRP : 0) + | (octal & XGRP ? S_IXGRP : 0) + | (octal & ROTH ? S_IROTH : 0) + | (octal & WOTH ? S_IWOTH : 0) + | (octal & XOTH ? S_IXOTH : 0))); +} + +/* Special operations flags. */ +enum + { + /* For the sentinel at the end of the mode changes array. */ + MODE_DONE, + + /* The typical case. */ + MODE_ORDINARY_CHANGE, + + /* In addition to the typical case, affect the execute bits if at + least one execute bit is set already, or if the file is a + directory. */ + MODE_X_IF_ANY_X, + + /* Instead of the typical case, copy some existing permissions for + u, g, or o onto the other two. Which of u, g, or o is copied + is determined by which bits are set in the `value' field. */ + MODE_COPY_EXISTING + }; + +/* Description of a mode change. */ +struct mode_change +{ + char op; /* One of "=+-". */ + char flag; /* Special operations flag. */ + mode_t affected; /* Set for u, g, o, or a. */ + mode_t value; /* Bits to add/remove. */ + mode_t mentioned; /* Bits explicitly mentioned. */ +}; + +/* Return a mode_change array with the specified `=ddd'-style + mode change operation, where NEW_MODE is `ddd' and MENTIONED + contains the bits explicitly mentioned in the mode are MENTIONED. */ + +static struct mode_change * +make_node_op_equals (mode_t new_mode, mode_t mentioned) +{ + struct mode_change *p = xmalloc (2 * sizeof *p); + p->op = '='; + p->flag = MODE_ORDINARY_CHANGE; + p->affected = CHMOD_MODE_BITS; + p->value = new_mode; + p->mentioned = mentioned; + p[1].flag = MODE_DONE; + return p; +} + +/* Return a pointer to an array of file mode change operations created from + MODE_STRING, an ASCII string that contains either an octal number + specifying an absolute mode, or symbolic mode change operations with + the form: + [ugoa...][[+-=][rwxXstugo...]...][,...] + + Return NULL if `mode_string' does not contain a valid + representation of file mode change operations. */ + +struct mode_change * +mode_compile (char const *mode_string) +{ + /* The array of mode-change directives to be returned. */ + struct mode_change *mc; + size_t used = 0; + + if ('0' <= *mode_string && *mode_string < '8') + { + unsigned int octal_mode = 0; + mode_t mode; + mode_t mentioned; + + do + { + octal_mode = 8 * octal_mode + *mode_string++ - '0'; + if (ALLM < octal_mode) + return NULL; + } + while ('0' <= *mode_string && *mode_string < '8'); + + if (*mode_string) + return NULL; + + mode = octal_to_mode (octal_mode); + mentioned = (mode & (S_ISUID | S_ISGID)) | S_ISVTX | S_IRWXUGO; + return make_node_op_equals (mode, mentioned); + } + + /* Allocate enough space to hold the result. */ + { + size_t needed = 1; + char const *p; + for (p = mode_string; *p; p++) + needed += (*p == '=' || *p == '+' || *p == '-'); + mc = xnmalloc (needed, sizeof *mc); + } + + /* One loop iteration for each `[ugoa]*([-+=]([rwxXst]*|[ugo]))+'. */ + for (;; mode_string++) + { + /* Which bits in the mode are operated on. */ + mode_t affected = 0; + + /* Turn on all the bits in `affected' for each group given. */ + for (;; mode_string++) + switch (*mode_string) + { + default: + goto invalid; + case 'u': + affected |= S_ISUID | S_IRWXU; + break; + case 'g': + affected |= S_ISGID | S_IRWXG; + break; + case 'o': + affected |= S_ISVTX | S_IRWXO; + break; + case 'a': + affected |= CHMOD_MODE_BITS; + break; + case '=': case '+': case '-': + goto no_more_affected; + } + no_more_affected:; + + do + { + char op = *mode_string++; + mode_t value; + char flag = MODE_COPY_EXISTING; + struct mode_change *change; + + switch (*mode_string++) + { + case 'u': + /* Set the affected bits to the value of the `u' bits + on the same file. */ + value = S_IRWXU; + break; + case 'g': + /* Set the affected bits to the value of the `g' bits + on the same file. */ + value = S_IRWXG; + break; + case 'o': + /* Set the affected bits to the value of the `o' bits + on the same file. */ + value = S_IRWXO; + break; + + default: + value = 0; + flag = MODE_ORDINARY_CHANGE; + + for (mode_string--;; mode_string++) + switch (*mode_string) + { + case 'r': + value |= S_IRUSR | S_IRGRP | S_IROTH; + break; + case 'w': + value |= S_IWUSR | S_IWGRP | S_IWOTH; + break; + case 'x': + value |= S_IXUSR | S_IXGRP | S_IXOTH; + break; + case 'X': + flag = MODE_X_IF_ANY_X; + break; + case 's': + /* Set the setuid/gid bits if `u' or `g' is selected. */ + value |= S_ISUID | S_ISGID; + break; + case 't': + /* Set the "save text image" bit if `o' is selected. */ + value |= S_ISVTX; + break; + default: + goto no_more_values; + } + no_more_values:; + } + + change = &mc[used++]; + change->op = op; + change->flag = flag; + change->affected = affected; + change->value = value; + change->mentioned = (affected ? affected & value : value); + } + while (*mode_string == '=' || *mode_string == '+' + || *mode_string == '-'); + + if (*mode_string != ',') + break; + } + + if (*mode_string == 0) + { + mc[used].flag = MODE_DONE; + return mc; + } + +invalid: + free (mc); + return NULL; +} + +/* Return a file mode change operation that sets permissions to match those + of REF_FILE. Return NULL (setting errno) if REF_FILE can't be accessed. */ + +struct mode_change * +mode_create_from_ref (const char *ref_file) +{ + struct stat ref_stats; + + if (stat (ref_file, &ref_stats) != 0) + return NULL; + return make_node_op_equals (ref_stats.st_mode, CHMOD_MODE_BITS); +} + +/* Return the file mode bits of OLDMODE (which is the mode of a + directory if DIR), assuming the umask is UMASK_VALUE, adjusted as + indicated by the list of change operations CHANGES. If DIR, the + type 'X' change affects the returned value even if no execute bits + were set in OLDMODE, and set user and group ID bits are preserved + unless CHANGES mentioned them. If PMODE_BITS is not null, store into + *PMODE_BITS a mask denoting file mode bits that are affected by + CHANGES. + + The returned value and *PMODE_BITS contain only file mode bits. + For example, they have the S_IFMT bits cleared on a standard + Unix-like host. */ + +mode_t +mode_adjust (mode_t oldmode, bool dir, mode_t umask_value, + struct mode_change const *changes, mode_t *pmode_bits) +{ + /* The adjusted mode. */ + mode_t newmode = oldmode & CHMOD_MODE_BITS; + + /* File mode bits that CHANGES cares about. */ + mode_t mode_bits = 0; + + for (; changes->flag != MODE_DONE; changes++) + { + mode_t affected = changes->affected; + mode_t omit_change = + (dir ? S_ISUID | S_ISGID : 0) & ~ changes->mentioned; + mode_t value = changes->value; + + switch (changes->flag) + { + case MODE_ORDINARY_CHANGE: + break; + + case MODE_COPY_EXISTING: + /* Isolate in `value' the bits in `newmode' to copy. */ + value &= newmode; + + /* Copy the isolated bits to the other two parts. */ + value |= ((value & (S_IRUSR | S_IRGRP | S_IROTH) + ? S_IRUSR | S_IRGRP | S_IROTH : 0) + | (value & (S_IWUSR | S_IWGRP | S_IWOTH) + ? S_IWUSR | S_IWGRP | S_IWOTH : 0) + | (value & (S_IXUSR | S_IXGRP | S_IXOTH) + ? S_IXUSR | S_IXGRP | S_IXOTH : 0)); + break; + + case MODE_X_IF_ANY_X: + /* Affect the execute bits if execute bits are already set + or if the file is a directory. */ + if ((newmode & (S_IXUSR | S_IXGRP | S_IXOTH)) | dir) + value |= S_IXUSR | S_IXGRP | S_IXOTH; + break; + } + + /* If WHO was specified, limit the change to the affected bits. + Otherwise, apply the umask. Either way, omit changes as + requested. */ + value &= (affected ? affected : ~umask_value) & ~ omit_change; + + switch (changes->op) + { + case '=': + /* If WHO was specified, preserve the previous values of + bits that are not affected by this change operation. + Otherwise, clear all the bits. */ + { + mode_t preserved = (affected ? ~affected : 0) | omit_change; + mode_bits |= CHMOD_MODE_BITS & ~preserved; + newmode = (newmode & preserved) | value; + break; + } + + case '+': + mode_bits |= value; + newmode |= value; + break; + + case '-': + mode_bits |= value; + newmode &= ~value; + break; + } + } + + if (pmode_bits) + *pmode_bits = mode_bits; + return newmode; +} diff --git a/src/bin/findutils/gnulib/lib/modechange.h b/src/bin/findutils/gnulib/lib/modechange.h new file mode 100644 index 0000000000..f6f8e744d6 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/modechange.h @@ -0,0 +1,30 @@ +/* modechange.h -- definitions for file mode manipulation + + Copyright (C) 1989, 1990, 1997, 2003, 2004, 2005, 2006 Free + Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#if ! defined MODECHANGE_H_ +# define MODECHANGE_H_ + +# include +# include + +struct mode_change *mode_compile (const char *); +struct mode_change *mode_create_from_ref (const char *); +mode_t mode_adjust (mode_t, bool, mode_t, struct mode_change const *, + mode_t *); + +#endif diff --git a/src/bin/findutils/gnulib/lib/mountlist.c b/src/bin/findutils/gnulib/lib/mountlist.c new file mode 100644 index 0000000000..4c975c63e9 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/mountlist.c @@ -0,0 +1,884 @@ +/* mountlist.c -- return a list of mounted file systems + + Copyright (C) 1991, 1992, 1997, 1998, 1999, 2000, 2001, 2002, 2003, + 2004, 2005, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "mountlist.h" + +#include +#include +#include +#include + +#include "xalloc.h" + +#include + +#include + +#include + +#if HAVE_SYS_PARAM_H +# include +#endif + +#if defined MOUNTED_GETFSSTAT /* OSF_1 and Darwin1.3.x */ +# if HAVE_SYS_UCRED_H +# include /* needed on OSF V4.0 for definition of NGROUPS, + NGROUPS is used as an array dimension in ucred.h */ +# include /* needed by powerpc-apple-darwin1.3.7 */ +# endif +# if HAVE_SYS_MOUNT_H +# include +# endif +# if HAVE_SYS_FS_TYPES_H +# include /* needed by powerpc-apple-darwin1.3.7 */ +# endif +# if HAVE_STRUCT_FSSTAT_F_FSTYPENAME +# define FS_TYPE(Ent) ((Ent).f_fstypename) +# else +# define FS_TYPE(Ent) mnt_names[(Ent).f_type] +# endif +#endif /* MOUNTED_GETFSSTAT */ + +#ifdef MOUNTED_GETMNTENT1 /* 4.3BSD, SunOS, HP-UX, Dynix, Irix. */ +# include +# if !defined MOUNTED +# if defined _PATH_MOUNTED /* GNU libc */ +# define MOUNTED _PATH_MOUNTED +# endif +# if defined MNT_MNTTAB /* HP-UX. */ +# define MOUNTED MNT_MNTTAB +# endif +# if defined MNTTABNAME /* Dynix. */ +# define MOUNTED MNTTABNAME +# endif +# endif +#endif + +#ifdef MOUNTED_GETMNTINFO /* 4.4BSD. */ +# include +#endif + +#ifdef MOUNTED_GETMNTINFO2 /* NetBSD 3.0. */ +# include +#endif + +#ifdef MOUNTED_GETMNT /* Ultrix. */ +# include +# include +#endif + +#ifdef MOUNTED_FS_STAT_DEV /* BeOS. */ +# include +# include +#endif + +#ifdef MOUNTED_FREAD /* SVR2. */ +# include +#endif + +#ifdef MOUNTED_FREAD_FSTYP /* SVR3. */ +# include +# include +# include +#endif + +#ifdef MOUNTED_LISTMNTENT +# include +#endif + +#ifdef MOUNTED_GETMNTENT2 /* SVR4. */ +# include +#endif + +#ifdef MOUNTED_VMOUNT /* AIX. */ +# include +# include +#endif + +#ifdef DOLPHIN +/* So special that it's not worth putting this in autoconf. */ +# undef MOUNTED_FREAD_FSTYP +# define MOUNTED_GETMNTTBL +#endif + +#if HAVE_SYS_MNTENT_H +/* This is to get MNTOPT_IGNORE on e.g. SVR4. */ +# include +#endif + +#undef MNT_IGNORE +#if defined MNTOPT_IGNORE && defined HAVE_HASMNTOPT +# define MNT_IGNORE(M) hasmntopt ((M), MNTOPT_IGNORE) +#else +# define MNT_IGNORE(M) 0 +#endif + +#if USE_UNLOCKED_IO +# include "unlocked-io.h" +#endif + +#ifndef SIZE_MAX +# define SIZE_MAX ((size_t) -1) +#endif + +/* The results of open() in this file are not used with fchdir, + therefore save some unnecessary work in fchdir.c. */ +#undef open +#undef close + +/* The results of opendir() in this file are not used with dirfd and fchdir, + therefore save some unnecessary work in fchdir.c. */ +#undef opendir +#undef closedir + +#ifndef ME_DUMMY +# define ME_DUMMY(Fs_name, Fs_type) \ + (strcmp (Fs_type, "autofs") == 0 \ + || strcmp (Fs_type, "none") == 0 \ + || strcmp (Fs_type, "proc") == 0 \ + || strcmp (Fs_type, "subfs") == 0 \ + /* for NetBSD 3.0 */ \ + || strcmp (Fs_type, "kernfs") == 0 \ + /* for Irix 6.5 */ \ + || strcmp (Fs_type, "ignore") == 0) +#endif + +#ifndef ME_REMOTE +/* A file system is `remote' if its Fs_name contains a `:' + or if (it is of type (smbfs or cifs) and its Fs_name starts with `//'). */ +# define ME_REMOTE(Fs_name, Fs_type) \ + (strchr (Fs_name, ':') != NULL \ + || ((Fs_name)[0] == '/' \ + && (Fs_name)[1] == '/' \ + && (strcmp (Fs_type, "smbfs") == 0 \ + || strcmp (Fs_type, "cifs") == 0))) +#endif + +#if MOUNTED_GETMNTINFO + +# if ! HAVE_STRUCT_STATFS_F_FSTYPENAME +static char * +fstype_to_string (short int t) +{ + switch (t) + { +# ifdef MOUNT_PC + case MOUNT_PC: + return "pc"; +# endif +# ifdef MOUNT_MFS + case MOUNT_MFS: + return "mfs"; +# endif +# ifdef MOUNT_LO + case MOUNT_LO: + return "lo"; +# endif +# ifdef MOUNT_TFS + case MOUNT_TFS: + return "tfs"; +# endif +# ifdef MOUNT_TMP + case MOUNT_TMP: + return "tmp"; +# endif +# ifdef MOUNT_UFS + case MOUNT_UFS: + return "ufs" ; +# endif +# ifdef MOUNT_NFS + case MOUNT_NFS: + return "nfs" ; +# endif +# ifdef MOUNT_MSDOS + case MOUNT_MSDOS: + return "msdos" ; +# endif +# ifdef MOUNT_LFS + case MOUNT_LFS: + return "lfs" ; +# endif +# ifdef MOUNT_LOFS + case MOUNT_LOFS: + return "lofs" ; +# endif +# ifdef MOUNT_FDESC + case MOUNT_FDESC: + return "fdesc" ; +# endif +# ifdef MOUNT_PORTAL + case MOUNT_PORTAL: + return "portal" ; +# endif +# ifdef MOUNT_NULL + case MOUNT_NULL: + return "null" ; +# endif +# ifdef MOUNT_UMAP + case MOUNT_UMAP: + return "umap" ; +# endif +# ifdef MOUNT_KERNFS + case MOUNT_KERNFS: + return "kernfs" ; +# endif +# ifdef MOUNT_PROCFS + case MOUNT_PROCFS: + return "procfs" ; +# endif +# ifdef MOUNT_AFS + case MOUNT_AFS: + return "afs" ; +# endif +# ifdef MOUNT_CD9660 + case MOUNT_CD9660: + return "cd9660" ; +# endif +# ifdef MOUNT_UNION + case MOUNT_UNION: + return "union" ; +# endif +# ifdef MOUNT_DEVFS + case MOUNT_DEVFS: + return "devfs" ; +# endif +# ifdef MOUNT_EXT2FS + case MOUNT_EXT2FS: + return "ext2fs" ; +# endif + default: + return "?"; + } +} +# endif + +static char * +fsp_to_string (const struct statfs *fsp) +{ +# if HAVE_STRUCT_STATFS_F_FSTYPENAME + return (char *) (fsp->f_fstypename); +# else + return fstype_to_string (fsp->f_type); +# endif +} + +#endif /* MOUNTED_GETMNTINFO */ + +#ifdef MOUNTED_VMOUNT /* AIX. */ +static char * +fstype_to_string (int t) +{ + struct vfs_ent *e; + + e = getvfsbytype (t); + if (!e || !e->vfsent_name) + return "none"; + else + return e->vfsent_name; +} +#endif /* MOUNTED_VMOUNT */ + + +#if defined MOUNTED_GETMNTENT1 || defined MOUNTED_GETMNTENT2 + +/* Return the device number from MOUNT_OPTIONS, if possible. + Otherwise return (dev_t) -1. */ + +static dev_t +dev_from_mount_options (char const *mount_options) +{ + /* GNU/Linux allows file system implementations to define their own + meaning for "dev=" mount options, so don't trust the meaning + here. */ +# ifndef __linux__ + + static char const dev_pattern[] = ",dev="; + char const *devopt = strstr (mount_options, dev_pattern); + + if (devopt) + { + char const *optval = devopt + sizeof dev_pattern - 1; + char *optvalend; + unsigned long int dev; + errno = 0; + dev = strtoul (optval, &optvalend, 16); + if (optval != optvalend + && (*optvalend == '\0' || *optvalend == ',') + && ! (dev == ULONG_MAX && errno == ERANGE) + && dev == (dev_t) dev) + return dev; + } + +# endif + + return -1; +} + +#endif + +/* Return a list of the currently mounted file systems, or NULL on error. + Add each entry to the tail of the list so that they stay in order. + If NEED_FS_TYPE is true, ensure that the file system type fields in + the returned list are valid. Otherwise, they might not be. */ + +struct mount_entry * +read_file_system_list (bool need_fs_type) +{ + struct mount_entry *mount_list; + struct mount_entry *me; + struct mount_entry **mtail = &mount_list; + +#ifdef MOUNTED_LISTMNTENT + { + struct tabmntent *mntlist, *p; + struct mntent *mnt; + struct mount_entry *me; + + /* the third and fourth arguments could be used to filter mounts, + but Crays doesn't seem to have any mounts that we want to + remove. Specifically, automount create normal NFS mounts. + */ + + if (listmntent (&mntlist, KMTAB, NULL, NULL) < 0) + return NULL; + for (p = mntlist; p; p = p->next) { + mnt = p->ment; + me = xmalloc (sizeof *me); + me->me_devname = xstrdup (mnt->mnt_fsname); + me->me_mountdir = xstrdup (mnt->mnt_dir); + me->me_type = xstrdup (mnt->mnt_type); + me->me_type_malloced = 1; + me->me_dummy = ME_DUMMY (me->me_devname, me->me_type); + me->me_remote = ME_REMOTE (me->me_devname, me->me_type); + me->me_dev = -1; + *mtail = me; + mtail = &me->me_next; + } + freemntlist (mntlist); + } +#endif + +#ifdef MOUNTED_GETMNTENT1 /* GNU/Linux, 4.3BSD, SunOS, HP-UX, Dynix, Irix. */ + { + struct mntent *mnt; + char *table = MOUNTED; + FILE *fp; + + fp = setmntent (table, "r"); + if (fp == NULL) + return NULL; + + while ((mnt = getmntent (fp))) + { + me = xmalloc (sizeof *me); + me->me_devname = xstrdup (mnt->mnt_fsname); + me->me_mountdir = xstrdup (mnt->mnt_dir); + me->me_type = xstrdup (mnt->mnt_type); + me->me_type_malloced = 1; + me->me_dummy = ME_DUMMY (me->me_devname, me->me_type); + me->me_remote = ME_REMOTE (me->me_devname, me->me_type); + me->me_dev = dev_from_mount_options (mnt->mnt_opts); + + /* Add to the linked list. */ + *mtail = me; + mtail = &me->me_next; + } + + if (endmntent (fp) == 0) + goto free_then_fail; + } +#endif /* MOUNTED_GETMNTENT1. */ + +#ifdef MOUNTED_GETMNTINFO /* 4.4BSD. */ + { + struct statfs *fsp; + int entries; + + entries = getmntinfo (&fsp, MNT_NOWAIT); + if (entries < 0) + return NULL; + for (; entries-- > 0; fsp++) + { + char *fs_type = fsp_to_string (fsp); + + me = xmalloc (sizeof *me); + me->me_devname = xstrdup (fsp->f_mntfromname); + me->me_mountdir = xstrdup (fsp->f_mntonname); + me->me_type = fs_type; + me->me_type_malloced = 0; + me->me_dummy = ME_DUMMY (me->me_devname, me->me_type); + me->me_remote = ME_REMOTE (me->me_devname, me->me_type); + me->me_dev = (dev_t) -1; /* Magic; means not known yet. */ + + /* Add to the linked list. */ + *mtail = me; + mtail = &me->me_next; + } + } +#endif /* MOUNTED_GETMNTINFO */ + +#ifdef MOUNTED_GETMNTINFO2 /* NetBSD 3.0. */ + { + struct statvfs *fsp; + int entries; + + entries = getmntinfo (&fsp, MNT_NOWAIT); + if (entries < 0) + return NULL; + for (; entries-- > 0; fsp++) + { + me = xmalloc (sizeof *me); + me->me_devname = xstrdup (fsp->f_mntfromname); + me->me_mountdir = xstrdup (fsp->f_mntonname); + me->me_type = xstrdup (fsp->f_fstypename); + me->me_type_malloced = 1; + me->me_dummy = ME_DUMMY (me->me_devname, me->me_type); + me->me_remote = ME_REMOTE (me->me_devname, me->me_type); + me->me_dev = (dev_t) -1; /* Magic; means not known yet. */ + + /* Add to the linked list. */ + *mtail = me; + mtail = &me->me_next; + } + } +#endif /* MOUNTED_GETMNTINFO2 */ + +#ifdef MOUNTED_GETMNT /* Ultrix. */ + { + int offset = 0; + int val; + struct fs_data fsd; + + while (errno = 0, + 0 < (val = getmnt (&offset, &fsd, sizeof (fsd), NOSTAT_MANY, + (char *) 0))) + { + me = xmalloc (sizeof *me); + me->me_devname = xstrdup (fsd.fd_req.devname); + me->me_mountdir = xstrdup (fsd.fd_req.path); + me->me_type = gt_names[fsd.fd_req.fstype]; + me->me_type_malloced = 0; + me->me_dummy = ME_DUMMY (me->me_devname, me->me_type); + me->me_remote = ME_REMOTE (me->me_devname, me->me_type); + me->me_dev = fsd.fd_req.dev; + + /* Add to the linked list. */ + *mtail = me; + mtail = &me->me_next; + } + if (val < 0) + goto free_then_fail; + } +#endif /* MOUNTED_GETMNT. */ + +#if defined MOUNTED_FS_STAT_DEV /* BeOS */ + { + /* The next_dev() and fs_stat_dev() system calls give the list of + all file systems, including the information returned by statvfs() + (fs type, total blocks, free blocks etc.), but without the mount + point. But on BeOS all file systems except / are mounted in the + rootfs, directly under /. + The directory name of the mount point is often, but not always, + identical to the volume name of the device. + We therefore get the list of subdirectories of /, and the list + of all file systems, and match the two lists. */ + + DIR *dirp; + struct rootdir_entry + { + char *name; + dev_t dev; + ino_t ino; + struct rootdir_entry *next; + }; + struct rootdir_entry *rootdir_list; + struct rootdir_entry **rootdir_tail; + int32 pos; + dev_t dev; + fs_info fi; + + /* All volumes are mounted in the rootfs, directly under /. */ + rootdir_list = NULL; + rootdir_tail = &rootdir_list; + dirp = opendir ("/"); + if (dirp) + { + struct dirent *d; + + while ((d = readdir (dirp)) != NULL) + { + char *name; + struct stat statbuf; + + if (strcmp (d->d_name, "..") == 0) + continue; + + if (strcmp (d->d_name, ".") == 0) + name = xstrdup ("/"); + else + { + name = xmalloc (1 + strlen (d->d_name) + 1); + name[0] = '/'; + strcpy (name + 1, d->d_name); + } + + if (lstat (name, &statbuf) >= 0 && S_ISDIR (statbuf.st_mode)) + { + struct rootdir_entry *re = xmalloc (sizeof *re); + re->name = name; + re->dev = statbuf.st_dev; + re->ino = statbuf.st_ino; + + /* Add to the linked list. */ + *rootdir_tail = re; + rootdir_tail = &re->next; + } + else + free (name); + } + closedir (dirp); + } + *rootdir_tail = NULL; + + for (pos = 0; (dev = next_dev (&pos)) >= 0; ) + if (fs_stat_dev (dev, &fi) >= 0) + { + /* Note: fi.dev == dev. */ + struct rootdir_entry *re; + + for (re = rootdir_list; re; re = re->next) + if (re->dev == fi.dev && re->ino == fi.root) + break; + + me = xmalloc (sizeof *me); + me->me_devname = xstrdup (fi.device_name[0] != '\0' ? fi.device_name : fi.fsh_name); + me->me_mountdir = xstrdup (re != NULL ? re->name : fi.fsh_name); + me->me_type = xstrdup (fi.fsh_name); + me->me_type_malloced = 1; + me->me_dev = fi.dev; + me->me_dummy = 0; + me->me_remote = (fi.flags & B_FS_IS_SHARED) != 0; + + /* Add to the linked list. */ + *mtail = me; + mtail = &me->me_next; + } + *mtail = NULL; + + while (rootdir_list != NULL) + { + struct rootdir_entry *re = rootdir_list; + rootdir_list = re->next; + free (re->name); + free (re); + } + } +#endif /* MOUNTED_FS_STAT_DEV */ + +#if defined MOUNTED_GETFSSTAT /* __alpha running OSF_1 */ + { + int numsys, counter; + size_t bufsize; + struct statfs *stats; + + numsys = getfsstat ((struct statfs *)0, 0L, MNT_NOWAIT); + if (numsys < 0) + return (NULL); + if (SIZE_MAX / sizeof *stats <= numsys) + xalloc_die (); + + bufsize = (1 + numsys) * sizeof *stats; + stats = xmalloc (bufsize); + numsys = getfsstat (stats, bufsize, MNT_NOWAIT); + + if (numsys < 0) + { + free (stats); + return (NULL); + } + + for (counter = 0; counter < numsys; counter++) + { + me = xmalloc (sizeof *me); + me->me_devname = xstrdup (stats[counter].f_mntfromname); + me->me_mountdir = xstrdup (stats[counter].f_mntonname); + me->me_type = xstrdup (FS_TYPE (stats[counter])); + me->me_type_malloced = 1; + me->me_dummy = ME_DUMMY (me->me_devname, me->me_type); + me->me_remote = ME_REMOTE (me->me_devname, me->me_type); + me->me_dev = (dev_t) -1; /* Magic; means not known yet. */ + + /* Add to the linked list. */ + *mtail = me; + mtail = &me->me_next; + } + + free (stats); + } +#endif /* MOUNTED_GETFSSTAT */ + +#if defined MOUNTED_FREAD || defined MOUNTED_FREAD_FSTYP /* SVR[23]. */ + { + struct mnttab mnt; + char *table = "/etc/mnttab"; + FILE *fp; + + fp = fopen (table, "r"); + if (fp == NULL) + return NULL; + + while (fread (&mnt, sizeof mnt, 1, fp) > 0) + { + me = xmalloc (sizeof *me); +# ifdef GETFSTYP /* SVR3. */ + me->me_devname = xstrdup (mnt.mt_dev); +# else + me->me_devname = xmalloc (strlen (mnt.mt_dev) + 6); + strcpy (me->me_devname, "/dev/"); + strcpy (me->me_devname + 5, mnt.mt_dev); +# endif + me->me_mountdir = xstrdup (mnt.mt_filsys); + me->me_dev = (dev_t) -1; /* Magic; means not known yet. */ + me->me_type = ""; + me->me_type_malloced = 0; +# ifdef GETFSTYP /* SVR3. */ + if (need_fs_type) + { + struct statfs fsd; + char typebuf[FSTYPSZ]; + + if (statfs (me->me_mountdir, &fsd, sizeof fsd, 0) != -1 + && sysfs (GETFSTYP, fsd.f_fstyp, typebuf) != -1) + { + me->me_type = xstrdup (typebuf); + me->me_type_malloced = 1; + } + } +# endif + me->me_dummy = ME_DUMMY (me->me_devname, me->me_type); + me->me_remote = ME_REMOTE (me->me_devname, me->me_type); + + /* Add to the linked list. */ + *mtail = me; + mtail = &me->me_next; + } + + if (ferror (fp)) + { + /* The last fread() call must have failed. */ + int saved_errno = errno; + fclose (fp); + errno = saved_errno; + goto free_then_fail; + } + + if (fclose (fp) == EOF) + goto free_then_fail; + } +#endif /* MOUNTED_FREAD || MOUNTED_FREAD_FSTYP. */ + +#ifdef MOUNTED_GETMNTTBL /* DolphinOS goes its own way. */ + { + struct mntent **mnttbl = getmnttbl (), **ent; + for (ent=mnttbl;*ent;ent++) + { + me = xmalloc (sizeof *me); + me->me_devname = xstrdup ( (*ent)->mt_resource); + me->me_mountdir = xstrdup ( (*ent)->mt_directory); + me->me_type = xstrdup ((*ent)->mt_fstype); + me->me_type_malloced = 1; + me->me_dummy = ME_DUMMY (me->me_devname, me->me_type); + me->me_remote = ME_REMOTE (me->me_devname, me->me_type); + me->me_dev = (dev_t) -1; /* Magic; means not known yet. */ + + /* Add to the linked list. */ + *mtail = me; + mtail = &me->me_next; + } + endmnttbl (); + } +#endif + +#ifdef MOUNTED_GETMNTENT2 /* SVR4. */ + { + struct mnttab mnt; + char *table = MNTTAB; + FILE *fp; + int ret; + int lockfd = -1; + +# if defined F_RDLCK && defined F_SETLKW + /* MNTTAB_LOCK is a macro name of our own invention; it's not present in + e.g. Solaris 2.6. If the SVR4 folks ever define a macro + for this file name, we should use their macro name instead. + (Why not just lock MNTTAB directly? We don't know.) */ +# ifndef MNTTAB_LOCK +# define MNTTAB_LOCK "/etc/.mnttab.lock" +# endif + lockfd = open (MNTTAB_LOCK, O_RDONLY); + if (0 <= lockfd) + { + struct flock flock; + flock.l_type = F_RDLCK; + flock.l_whence = SEEK_SET; + flock.l_start = 0; + flock.l_len = 0; + while (fcntl (lockfd, F_SETLKW, &flock) == -1) + if (errno != EINTR) + { + int saved_errno = errno; + close (lockfd); + errno = saved_errno; + return NULL; + } + } + else if (errno != ENOENT) + return NULL; +# endif + + errno = 0; + fp = fopen (table, "r"); + if (fp == NULL) + ret = errno; + else + { + while ((ret = getmntent (fp, &mnt)) == 0) + { + me = xmalloc (sizeof *me); + me->me_devname = xstrdup (mnt.mnt_special); + me->me_mountdir = xstrdup (mnt.mnt_mountp); + me->me_type = xstrdup (mnt.mnt_fstype); + me->me_type_malloced = 1; + me->me_dummy = MNT_IGNORE (&mnt) != 0; + me->me_remote = ME_REMOTE (me->me_devname, me->me_type); + me->me_dev = dev_from_mount_options (mnt.mnt_mntopts); + + /* Add to the linked list. */ + *mtail = me; + mtail = &me->me_next; + } + + ret = fclose (fp) == EOF ? errno : 0 < ret ? 0 : -1; + } + + if (0 <= lockfd && close (lockfd) != 0) + ret = errno; + + if (0 <= ret) + { + errno = ret; + goto free_then_fail; + } + } +#endif /* MOUNTED_GETMNTENT2. */ + +#ifdef MOUNTED_VMOUNT /* AIX. */ + { + int bufsize; + char *entries, *thisent; + struct vmount *vmp; + int n_entries; + int i; + + /* Ask how many bytes to allocate for the mounted file system info. */ + if (mntctl (MCTL_QUERY, sizeof bufsize, (struct vmount *) &bufsize) != 0) + return NULL; + entries = xmalloc (bufsize); + + /* Get the list of mounted file systems. */ + n_entries = mntctl (MCTL_QUERY, bufsize, (struct vmount *) entries); + if (n_entries < 0) + { + int saved_errno = errno; + free (entries); + errno = saved_errno; + return NULL; + } + + for (i = 0, thisent = entries; + i < n_entries; + i++, thisent += vmp->vmt_length) + { + char *options, *ignore; + + vmp = (struct vmount *) thisent; + me = xmalloc (sizeof *me); + if (vmp->vmt_flags & MNT_REMOTE) + { + char *host, *dir; + + me->me_remote = 1; + /* Prepend the remote dirname. */ + host = thisent + vmp->vmt_data[VMT_HOSTNAME].vmt_off; + dir = thisent + vmp->vmt_data[VMT_OBJECT].vmt_off; + me->me_devname = xmalloc (strlen (host) + strlen (dir) + 2); + strcpy (me->me_devname, host); + strcat (me->me_devname, ":"); + strcat (me->me_devname, dir); + } + else + { + me->me_remote = 0; + me->me_devname = xstrdup (thisent + + vmp->vmt_data[VMT_OBJECT].vmt_off); + } + me->me_mountdir = xstrdup (thisent + vmp->vmt_data[VMT_STUB].vmt_off); + me->me_type = xstrdup (fstype_to_string (vmp->vmt_gfstype)); + me->me_type_malloced = 1; + options = thisent + vmp->vmt_data[VMT_ARGS].vmt_off; + ignore = strstr (options, "ignore"); + me->me_dummy = (ignore + && (ignore == options || ignore[-1] == ',') + && (ignore[sizeof "ignore" - 1] == ',' + || ignore[sizeof "ignore" - 1] == '\0')); + me->me_dev = (dev_t) -1; /* vmt_fsid might be the info we want. */ + + /* Add to the linked list. */ + *mtail = me; + mtail = &me->me_next; + } + free (entries); + } +#endif /* MOUNTED_VMOUNT. */ + + *mtail = NULL; + return mount_list; + + + free_then_fail: + { + int saved_errno = errno; + *mtail = NULL; + + while (mount_list) + { + me = mount_list->me_next; + free (mount_list->me_devname); + free (mount_list->me_mountdir); + if (mount_list->me_type_malloced) + free (mount_list->me_type); + free (mount_list); + mount_list = me; + } + + errno = saved_errno; + return NULL; + } +} diff --git a/src/bin/findutils/gnulib/lib/mountlist.h b/src/bin/findutils/gnulib/lib/mountlist.h new file mode 100644 index 0000000000..e54bb49ef8 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/mountlist.h @@ -0,0 +1,40 @@ +/* mountlist.h -- declarations for list of mounted file systems + + Copyright (C) 1991, 1992, 1998, 2000, 2001, 2002, 2003, 2004, 2005 + Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef MOUNTLIST_H_ +# define MOUNTLIST_H_ + +# include +# include + +/* A mount table entry. */ +struct mount_entry +{ + char *me_devname; /* Device node name, including "/dev/". */ + char *me_mountdir; /* Mount point directory name. */ + char *me_type; /* "nfs", "4.2", etc. */ + dev_t me_dev; /* Device number of me_mountdir. */ + unsigned int me_dummy : 1; /* Nonzero for dummy file systems. */ + unsigned int me_remote : 1; /* Nonzero for remote fileystems. */ + unsigned int me_type_malloced : 1; /* Nonzero if me_type was malloced. */ + struct mount_entry *me_next; +}; + +struct mount_entry *read_file_system_list (bool need_fs_type); + +#endif diff --git a/src/bin/findutils/gnulib/lib/open-safer.c b/src/bin/findutils/gnulib/lib/open-safer.c new file mode 100644 index 0000000000..ce493d5e31 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/open-safer.c @@ -0,0 +1,49 @@ +/* Invoke open, but avoid some glitches. + + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert. */ + +#include + +#include "fcntl-safer.h" + +#include +#include +#include "unistd-safer.h" + +int +open_safer (char const *file, int flags, ...) +{ + mode_t mode = 0; + + if (flags & O_CREAT) + { + va_list ap; + va_start (ap, flags); + + /* Assume mode_t promotes to int if and only if it is smaller. + This assumption isn't guaranteed by the C standard, but we + don't know of any real-world counterexamples. */ + mode = (sizeof (mode_t) < sizeof (int) + ? va_arg (ap, int) + : va_arg (ap, mode_t)); + + va_end (ap); + } + + return fd_safer (open (file, flags, mode)); +} diff --git a/src/bin/findutils/gnulib/lib/openat-die.c b/src/bin/findutils/gnulib/lib/openat-die.c new file mode 100644 index 0000000000..6bc533d07f --- /dev/null +++ b/src/bin/findutils/gnulib/lib/openat-die.c @@ -0,0 +1,50 @@ +/* Report a save- or restore-cwd failure in our openat replacement and then exit. + + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include + +#include "error.h" +#include "exitfail.h" + +#include "gettext.h" +#define _(msgid) gettext (msgid) +#define N_(msgid) msgid + +void +openat_save_fail (int errno) +{ + error (exit_failure, errno, + _("unable to record current working directory")); + + /* The `noreturn' attribute cannot be applied to error, since it returns + when its first argument is 0. To help compilers understand that this + function does not return, call abort. Also, the abort is a + safety feature if exit_failure is 0 (which shouldn't happen). */ + abort (); +} + +void +openat_restore_fail (int errno) +{ + error (exit_failure, errno, + _("failed to return to initial working directory")); + + /* As above. */ + abort (); +} diff --git a/src/bin/findutils/gnulib/lib/openat-priv.h b/src/bin/findutils/gnulib/lib/openat-priv.h new file mode 100644 index 0000000000..9254f6bbad --- /dev/null +++ b/src/bin/findutils/gnulib/lib/openat-priv.h @@ -0,0 +1,54 @@ +/* Internals for openat-like functions. + + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include +#include + +#define OPENAT_BUFFER_SIZE 512 +char *openat_proc_name (char buf[OPENAT_BUFFER_SIZE], int fd, char const *file); + +/* Some systems don't have ENOSYS. */ +#ifndef ENOSYS +# ifdef ENOTSUP +# define ENOSYS ENOTSUP +# else +/* Some systems don't have ENOTSUP either. */ +# define ENOSYS EINVAL +# endif +#endif + +/* Some systems don't have EOPNOTSUPP. */ +#ifndef EOPNOTSUPP +# ifdef ENOTSUP +# define EOPNOTSUPP ENOTSUP +# else +/* Some systems don't have ENOTSUP either. */ +# define EOPNOTSUPP EINVAL +# endif +#endif + +/* Trying to access a BUILD_PROC_NAME file will fail on systems without + /proc support, and even on systems *with* ProcFS support. Return + nonzero if the failure may be legitimate, e.g., because /proc is not + readable, or the particular .../fd/N directory is not present. */ +#define EXPECTED_ERRNO(Errno) \ + ((Errno) == ENOTDIR || (Errno) == ENOENT \ + || (Errno) == EPERM || (Errno) == EACCES \ + || (Errno) == ENOSYS /* Solaris 8 */ \ + || (Errno) == EOPNOTSUPP /* FreeBSD */) diff --git a/src/bin/findutils/gnulib/lib/openat-proc.c b/src/bin/findutils/gnulib/lib/openat-proc.c new file mode 100644 index 0000000000..e84dc454fb --- /dev/null +++ b/src/bin/findutils/gnulib/lib/openat-proc.c @@ -0,0 +1,94 @@ +/* Create /proc/self/fd-related names for subfiles of open directories. + + Copyright (C) 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert. */ + +#include + +#include "openat-priv.h" + +#include +#include +#include + +#include +#include + +#include "dirname.h" +#include "intprops.h" +#include "same-inode.h" +#include "xalloc.h" + +/* The results of open() in this file are not used with fchdir, + therefore save some unnecessary work in fchdir.c. */ +#undef open +#undef close + +#define PROC_SELF_FD_FORMAT "/proc/self/fd/%d/%s" + +#define PROC_SELF_FD_NAME_SIZE_BOUND(len) \ + (sizeof PROC_SELF_FD_FORMAT - sizeof "%d%s" \ + + INT_STRLEN_BOUND (int) + (len) + 1) + + +/* Set BUF to the expansion of PROC_SELF_FD_FORMAT, using FD and FILE + respectively for %d and %s. If successful, return BUF if the + result fits in BUF, dynamically allocated memory otherwise. But + return NULL if /proc is not reliable. */ +char * +openat_proc_name (char buf[OPENAT_BUFFER_SIZE], int fd, char const *file) +{ + static int proc_status = 0; + + if (! proc_status) + { + /* Set PROC_STATUS to a positive value if /proc/self/fd is + reliable, and a negative value otherwise. Solaris 10 + /proc/self/fd mishandles "..", and any file name might expand + to ".." after symbolic link expansion, so avoid /proc/self/fd + if it mishandles "..". Solaris 10 has openat, but this + problem is exhibited on code that built on Solaris 8 and + running on Solaris 10. */ + + int proc_self_fd = open ("/proc/self/fd", O_RDONLY); + if (proc_self_fd < 0) + proc_status = -1; + else + { + struct stat proc_self_fd_dotdot_st; + struct stat proc_self_st; + char dotdot_buf[PROC_SELF_FD_NAME_SIZE_BOUND (sizeof ".." - 1)]; + sprintf (dotdot_buf, PROC_SELF_FD_FORMAT, proc_self_fd, ".."); + proc_status = + ((stat (dotdot_buf, &proc_self_fd_dotdot_st) == 0 + && stat ("/proc/self", &proc_self_st) == 0 + && SAME_INODE (proc_self_fd_dotdot_st, proc_self_st)) + ? 1 : -1); + close (proc_self_fd); + } + } + + if (proc_status < 0) + return NULL; + else + { + size_t bufsize = PROC_SELF_FD_NAME_SIZE_BOUND (strlen (file)); + char *result = (bufsize < OPENAT_BUFFER_SIZE ? buf : xmalloc (bufsize)); + sprintf (result, PROC_SELF_FD_FORMAT, fd, file); + return result; + } +} diff --git a/src/bin/findutils/gnulib/lib/openat.c b/src/bin/findutils/gnulib/lib/openat.c new file mode 100644 index 0000000000..73f24b0697 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/openat.c @@ -0,0 +1,268 @@ +/* provide a replacement openat function + Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include + +#include "openat.h" + +#include +#include + +#include "dirname.h" /* solely for definition of IS_ABSOLUTE_FILE_NAME */ +#include "fcntl--.h" +#include "lstat.h" +#include "openat-priv.h" +#include "save-cwd.h" + +/* Replacement for Solaris' openat function. + + First, try to simulate it via open ("/proc/self/fd/FD/FILE"). + Failing that, simulate it by doing save_cwd/fchdir/open/restore_cwd. + If either the save_cwd or the restore_cwd fails (relatively unlikely), + then give a diagnostic and exit nonzero. + Otherwise, upon failure, set errno and return -1, as openat does. + Upon successful completion, return a file descriptor. */ +int +openat (int fd, char const *file, int flags, ...) +{ + mode_t mode = 0; + + if (flags & O_CREAT) + { + va_list arg; + va_start (arg, flags); + + /* If mode_t is narrower than int, use the promoted type (int), + not mode_t. Use sizeof to guess whether mode_t is narrower; + we don't know of any practical counterexamples. */ + mode = (sizeof (mode_t) < sizeof (int) + ? va_arg (arg, int) + : va_arg (arg, mode_t)); + + va_end (arg); + } + + return openat_permissive (fd, file, flags, mode, NULL); +} + +/* Like openat (FD, FILE, FLAGS, MODE), but if CWD_ERRNO is + nonnull, set *CWD_ERRNO to an errno value if unable to save + or restore the initial working directory. This is needed only + the first time remove.c's remove_dir opens a command-line + directory argument. + + If a previous attempt to restore the current working directory + failed, then we must not even try to access a `.'-relative name. + It is the caller's responsibility not to call this function + in that case. */ + +int +openat_permissive (int fd, char const *file, int flags, mode_t mode, + int *cwd_errno) +{ + struct saved_cwd saved_cwd; + int saved_errno; + int err; + bool save_ok; + + if (fd == AT_FDCWD || IS_ABSOLUTE_FILE_NAME (file)) + return open (file, flags, mode); + + { + char buf[OPENAT_BUFFER_SIZE]; + char *proc_file = openat_proc_name (buf, fd, file); + if (proc_file) + { + int open_result = open (proc_file, flags, mode); + int open_errno = errno; + if (proc_file != buf) + free (proc_file); + /* If the syscall succeeds, or if it fails with an unexpected + errno value, then return right away. Otherwise, fall through + and resort to using save_cwd/restore_cwd. */ + if (0 <= open_result || ! EXPECTED_ERRNO (open_errno)) + { + errno = open_errno; + return open_result; + } + } + } + + save_ok = (save_cwd (&saved_cwd) == 0); + if (! save_ok) + { + if (! cwd_errno) + openat_save_fail (errno); + *cwd_errno = errno; + } + + err = fchdir (fd); + saved_errno = errno; + + if (! err) + { + err = open (file, flags, mode); + saved_errno = errno; + if (save_ok && restore_cwd (&saved_cwd) != 0) + { + if (! cwd_errno) + openat_restore_fail (errno); + *cwd_errno = errno; + } + } + + free_cwd (&saved_cwd); + errno = saved_errno; + return err; +} + +/* Return true if our openat implementation must resort to + using save_cwd and restore_cwd. */ +bool +openat_needs_fchdir (void) +{ + bool needs_fchdir = true; + int fd = open ("/", O_RDONLY); + + if (0 <= fd) + { + char buf[OPENAT_BUFFER_SIZE]; + char *proc_file = openat_proc_name (buf, fd, "."); + if (proc_file) + { + needs_fchdir = false; + if (proc_file != buf) + free (proc_file); + } + close (fd); + } + + return needs_fchdir; +} + +#if !HAVE_FDOPENDIR + +/* Replacement for Solaris' function by the same name. + + First, try to simulate it via opendir ("/proc/self/fd/FD"). Failing + that, simulate it by doing save_cwd/fchdir/opendir(".")/restore_cwd. + If either the save_cwd or the restore_cwd fails (relatively unlikely), + then give a diagnostic and exit nonzero. + Otherwise, this function works just like Solaris' fdopendir. + + W A R N I N G: + Unlike the other fd-related functions here, this one + effectively consumes its FD parameter. The caller should not + close or otherwise manipulate FD if this function returns successfully. */ +DIR * +fdopendir (int fd) +{ + struct saved_cwd saved_cwd; + int saved_errno; + DIR *dir; + + char buf[OPENAT_BUFFER_SIZE]; + char *proc_file = openat_proc_name (buf, fd, "."); + if (proc_file) + { + dir = opendir (proc_file); + saved_errno = errno; + } + else + { + dir = NULL; + saved_errno = EOPNOTSUPP; + } + + /* If the syscall fails with an expected errno value, resort to + save_cwd/restore_cwd. */ + if (! dir && EXPECTED_ERRNO (saved_errno)) + { + if (save_cwd (&saved_cwd) != 0) + openat_save_fail (errno); + + if (fchdir (fd) != 0) + { + dir = NULL; + saved_errno = errno; + } + else + { + dir = opendir ("."); + saved_errno = errno; + + if (restore_cwd (&saved_cwd) != 0) + openat_restore_fail (errno); + } + + free_cwd (&saved_cwd); + } + + if (dir) + close (fd); + if (proc_file != buf) + free (proc_file); + errno = saved_errno; + return dir; +} + +#endif + +/* Replacement for Solaris' function by the same name. + + First, try to simulate it via l?stat ("/proc/self/fd/FD/FILE"). + Failing that, simulate it via save_cwd/fchdir/(stat|lstat)/restore_cwd. + If either the save_cwd or the restore_cwd fails (relatively unlikely), + then give a diagnostic and exit nonzero. + Otherwise, this function works just like Solaris' fstatat. */ + +#define AT_FUNC_NAME fstatat +#define AT_FUNC_F1 lstat +#define AT_FUNC_F2 stat +#define AT_FUNC_USE_F1_COND flag == AT_SYMLINK_NOFOLLOW +#define AT_FUNC_POST_FILE_PARAM_DECLS , struct stat *st, int flag +#define AT_FUNC_POST_FILE_ARGS , st +#include "at-func.c" +#undef AT_FUNC_NAME +#undef AT_FUNC_F1 +#undef AT_FUNC_F2 +#undef AT_FUNC_USE_F1_COND +#undef AT_FUNC_POST_FILE_PARAM_DECLS +#undef AT_FUNC_POST_FILE_ARGS + +/* Replacement for Solaris' function by the same name. + + First, try to simulate it via (unlink|rmdir) ("/proc/self/fd/FD/FILE"). + Failing that, simulate it via save_cwd/fchdir/(unlink|rmdir)/restore_cwd. + If either the save_cwd or the restore_cwd fails (relatively unlikely), + then give a diagnostic and exit nonzero. + Otherwise, this function works just like Solaris' unlinkat. */ + +#define AT_FUNC_NAME unlinkat +#define AT_FUNC_F1 rmdir +#define AT_FUNC_F2 unlink +#define AT_FUNC_USE_F1_COND flag == AT_REMOVEDIR +#define AT_FUNC_POST_FILE_PARAM_DECLS , int flag +#define AT_FUNC_POST_FILE_ARGS /* empty */ +#include "at-func.c" +#undef AT_FUNC_NAME +#undef AT_FUNC_F1 +#undef AT_FUNC_F2 +#undef AT_FUNC_USE_F1_COND +#undef AT_FUNC_POST_FILE_PARAM_DECLS +#undef AT_FUNC_POST_FILE_ARGS diff --git a/src/bin/findutils/gnulib/lib/openat.h b/src/bin/findutils/gnulib/lib/openat.h new file mode 100644 index 0000000000..b5e4f116c9 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/openat.h @@ -0,0 +1,126 @@ +/* provide a replacement openat function + Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include + +#include +#include +#include +#include +#include + +#ifndef __attribute__ +# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__ +# define __attribute__(x) /* empty */ +# endif +#endif + +#ifndef ATTRIBUTE_NORETURN +# define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__)) +#endif + +/* Work around a bug in Solaris 9 and 10: AT_FDCWD is positive. Its + value exceeds INT_MAX, so its use as an int doesn't conform to the + C standard, and GCC and Sun C complain in some cases. If the bug + is present, undef AT_FDCWD here, so it can be redefined below. */ +#if 0 < AT_FDCWD && AT_FDCWD == 0xffd19553 +# undef AT_FDCWD +#endif + +/* Use the same bit pattern as Solaris 9, but with the proper + signedness. The bit pattern is important, in case this actually is + Solaris with the above workaround. */ +#ifndef AT_FDCWD +# define AT_FDCWD (-3041965) +#endif + +/* Use the same values as Solaris 9. This shouldn't matter, but + there's no real reason to differ. */ +#ifndef AT_SYMLINK_NOFOLLOW +# define AT_SYMLINK_NOFOLLOW 4096 +# define AT_REMOVEDIR 1 +#endif + +#ifdef __OPENAT_PREFIX + +# undef openat +# define __OPENAT_CONCAT(x, y) x ## y +# define __OPENAT_XCONCAT(x, y) __OPENAT_CONCAT (x, y) +# define __OPENAT_ID(y) __OPENAT_XCONCAT (__OPENAT_PREFIX, y) +# define openat __OPENAT_ID (openat) +int openat (int fd, char const *file, int flags, /* mode_t mode */ ...); +int openat_permissive (int fd, char const *file, int flags, mode_t mode, + int *cwd_errno); +# if ! HAVE_FDOPENDIR +# define fdopendir __OPENAT_ID (fdopendir) +# endif +DIR *fdopendir (int fd); +# define fstatat __OPENAT_ID (fstatat) +int fstatat (int fd, char const *file, struct stat *st, int flag); +# define unlinkat __OPENAT_ID (unlinkat) +int unlinkat (int fd, char const *file, int flag); +bool openat_needs_fchdir (void); + +#else + +# define openat_permissive(Fd, File, Flags, Mode, Cwd_errno) \ + openat (Fd, File, Flags, Mode) +# define openat_needs_fchdir() false + +#endif + +#if HAVE_OPENAT && ! LSTAT_FOLLOWS_SLASHED_SYMLINK +int rpl_fstatat (int fd, char const *file, struct stat *st, int flag); +# if !COMPILING_FSTATAT +# undef fstatat +# define fstatat rpl_fstatat +# endif +#endif + +int mkdirat (int fd, char const *file, mode_t mode); +void openat_restore_fail (int) ATTRIBUTE_NORETURN; +void openat_save_fail (int) ATTRIBUTE_NORETURN; +int fchmodat (int fd, char const *file, mode_t mode, int flag); +int fchownat (int fd, char const *file, uid_t owner, gid_t group, int flag); + +/* Using these function names makes application code + slightly more readable than it would be with + fchownat (..., 0) or fchownat (..., AT_SYMLINK_NOFOLLOW). */ +static inline int +chownat (int fd, char const *file, uid_t owner, gid_t group) +{ + return fchownat (fd, file, owner, group, 0); +} + +static inline int +lchownat (int fd, char const *file, uid_t owner, gid_t group) +{ + return fchownat (fd, file, owner, group, AT_SYMLINK_NOFOLLOW); +} + +static inline int +chmodat (int fd, char const *file, mode_t mode) +{ + return fchmodat (fd, file, mode, 0); +} + +static inline int +lchmodat (int fd, char const *file, mode_t mode) +{ + return fchmodat (fd, file, mode, AT_SYMLINK_NOFOLLOW); +} diff --git a/src/bin/findutils/gnulib/lib/pathmax.h b/src/bin/findutils/gnulib/lib/pathmax.h new file mode 100644 index 0000000000..a653f26eef --- /dev/null +++ b/src/bin/findutils/gnulib/lib/pathmax.h @@ -0,0 +1,47 @@ +/* Define PATH_MAX somehow. Requires sys/types.h. + Copyright (C) 1992, 1999, 2001, 2003, 2005 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _PATHMAX_H +# define _PATHMAX_H + +# include + +# include + +# ifndef _POSIX_PATH_MAX +# define _POSIX_PATH_MAX 256 +# endif + +# if !defined PATH_MAX && defined _PC_PATH_MAX +# define PATH_MAX (pathconf ("/", _PC_PATH_MAX) < 1 ? 1024 \ + : pathconf ("/", _PC_PATH_MAX)) +# endif + +/* Don't include sys/param.h if it already has been. */ +# if defined HAVE_SYS_PARAM_H && !defined PATH_MAX && !defined MAXPATHLEN +# include +# endif + +# if !defined PATH_MAX && defined MAXPATHLEN +# define PATH_MAX MAXPATHLEN +# endif + +# ifndef PATH_MAX +# define PATH_MAX _POSIX_PATH_MAX +# endif + +#endif /* _PATHMAX_H */ diff --git a/src/bin/findutils/gnulib/lib/pipe-safer.c b/src/bin/findutils/gnulib/lib/pipe-safer.c new file mode 100644 index 0000000000..0fc685054b --- /dev/null +++ b/src/bin/findutils/gnulib/lib/pipe-safer.c @@ -0,0 +1,56 @@ +/* Invoke pipe, but avoid some glitches. + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Jim Meyering. */ + +#include + +#include "unistd-safer.h" + +#include +#include + +/* Like pipe, but ensure that neither of the file descriptors is + STDIN_FILENO, STDOUT_FILENO, or STDERR_FILENO. Fail with ENOSYS on + platforms that lack pipe. */ + +int +pipe_safer (int fd[2]) +{ +#if HAVE_PIPE + if (pipe (fd) == 0) + { + int i; + for (i = 0; i < 2; i++) + { + fd[i] = fd_safer (fd[i]); + if (fd[i] < 0) + { + int e = errno; + close (fd[1 - i]); + errno = e; + return -1; + } + } + + return 0; + } +#else + errno = ENOSYS; +#endif + + return -1; +} diff --git a/src/bin/findutils/gnulib/lib/progname.c b/src/bin/findutils/gnulib/lib/progname.c new file mode 100644 index 0000000000..fa5aa8bec7 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/progname.c @@ -0,0 +1,49 @@ +/* Program name management. + Copyright (C) 2001-2003, 2005-2006 Free Software Foundation, Inc. + Written by Bruno Haible , 2001. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + + +#include + +/* Specification. */ +#undef ENABLE_RELOCATABLE /* avoid defining set_program_name as a macro */ +#include "progname.h" + +#include + + +/* String containing name the program is called with. + To be initialized by main(). */ +const char *program_name = NULL; + +/* Set program_name, based on argv[0]. */ +void +set_program_name (const char *argv0) +{ + /* libtool creates a temporary executable whose name is sometimes prefixed + with "lt-" (depends on the platform). It also makes argv[0] absolute. + Remove this "/.libs/" or "/.libs/lt-" prefix here. */ + const char *slash; + const char *base; + + slash = strrchr (argv0, '/'); + base = (slash != NULL ? slash + 1 : argv0); + if (base - argv0 >= 7 && memcmp (base - 7, "/.libs/", 7) == 0) + argv0 = base; + if (strncmp (base, "lt-", 3) == 0) + argv0 = base + 3; + program_name = argv0; +} diff --git a/src/bin/findutils/gnulib/lib/progname.h b/src/bin/findutils/gnulib/lib/progname.h new file mode 100644 index 0000000000..82615c6bc0 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/progname.h @@ -0,0 +1,60 @@ +/* Program name management. + Copyright (C) 2001-2004, 2006 Free Software Foundation, Inc. + Written by Bruno Haible , 2001. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef _PROGNAME_H +#define _PROGNAME_H + +/* Programs using this file should do the following in main(): + set_program_name (argv[0]); + */ + + +#ifdef __cplusplus +extern "C" { +#endif + + +/* String containing name the program is called with. */ +extern const char *program_name; + +/* Set program_name, based on argv[0]. */ +extern void set_program_name (const char *argv0); + +#if ENABLE_RELOCATABLE + +/* Set program_name, based on argv[0], and original installation prefix and + directory, for relocatability. */ +extern void set_program_name_and_installdir (const char *argv0, + const char *orig_installprefix, + const char *orig_installdir); +#undef set_program_name +#define set_program_name(ARG0) \ + set_program_name_and_installdir (ARG0, INSTALLPREFIX, INSTALLDIR) + +/* Return the full pathname of the current executable, based on the earlier + call to set_program_name_and_installdir. Return NULL if unknown. */ +extern char *get_full_program_name (void); + +#endif + + +#ifdef __cplusplus +} +#endif + + +#endif /* _PROGNAME_H */ diff --git a/src/bin/findutils/gnulib/lib/quote.c b/src/bin/findutils/gnulib/lib/quote.c new file mode 100644 index 0000000000..5e8b764711 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/quote.c @@ -0,0 +1,40 @@ +/* quote.c - quote arguments for output + + Copyright (C) 1998, 1999, 2000, 2001, 2003, 2005, 2006 Free + Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert */ + +#include + +#include "quotearg.h" +#include "quote.h" + +/* Return an unambiguous printable representation of NAME, + allocated in slot N, suitable for diagnostics. */ +char const * +quote_n (int n, char const *name) +{ + return quotearg_n_style (n, locale_quoting_style, name); +} + +/* Return an unambiguous printable representation of NAME, + suitable for diagnostics. */ +char const * +quote (char const *name) +{ + return quote_n (0, name); +} diff --git a/src/bin/findutils/gnulib/lib/quote.h b/src/bin/findutils/gnulib/lib/quote.h new file mode 100644 index 0000000000..c3660b1963 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/quote.h @@ -0,0 +1,21 @@ +/* quote.h - prototypes for quote.c + + Copyright (C) 1998, 1999, 2000, 2001, 2003 Free Software + Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + + +char const *quote_n (int n, char const *name); +char const *quote (char const *name); diff --git a/src/bin/findutils/gnulib/lib/quotearg.c b/src/bin/findutils/gnulib/lib/quotearg.c new file mode 100644 index 0000000000..00d397c418 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/quotearg.c @@ -0,0 +1,696 @@ +/* quotearg.c - quote arguments for output + + Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006, 2007 Free + Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert */ + +#include + +#include "quotearg.h" + +#include "xalloc.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gettext.h" +#define _(msgid) gettext (msgid) +#define N_(msgid) msgid + +#if !HAVE_MBRTOWC +/* Disable multibyte processing entirely. Since MB_CUR_MAX is 1, the + other macros are defined only for documentation and to satisfy C + syntax. */ +# undef MB_CUR_MAX +# define MB_CUR_MAX 1 +# undef mbstate_t +# define mbstate_t int +# define mbrtowc(pwc, s, n, ps) ((*(pwc) = *(s)) != 0) +# define iswprint(wc) isprint ((unsigned char) (wc)) +# undef HAVE_MBSINIT +#endif + +#if !defined mbsinit && !HAVE_MBSINIT +# define mbsinit(ps) 1 +#endif + +#ifndef SIZE_MAX +# define SIZE_MAX ((size_t) -1) +#endif + +#define INT_BITS (sizeof (int) * CHAR_BIT) + +struct quoting_options +{ + /* Basic quoting style. */ + enum quoting_style style; + + /* Quote the characters indicated by this bit vector even if the + quoting style would not normally require them to be quoted. */ + unsigned int quote_these_too[(UCHAR_MAX / INT_BITS) + 1]; +}; + +/* Names of quoting styles. */ +char const *const quoting_style_args[] = +{ + "literal", + "shell", + "shell-always", + "c", + "escape", + "locale", + "clocale", + 0 +}; + +/* Correspondences to quoting style names. */ +enum quoting_style const quoting_style_vals[] = +{ + literal_quoting_style, + shell_quoting_style, + shell_always_quoting_style, + c_quoting_style, + escape_quoting_style, + locale_quoting_style, + clocale_quoting_style +}; + +/* The default quoting options. */ +static struct quoting_options default_quoting_options; + +/* Allocate a new set of quoting options, with contents initially identical + to O if O is not null, or to the default if O is null. + It is the caller's responsibility to free the result. */ +struct quoting_options * +clone_quoting_options (struct quoting_options *o) +{ + int e = errno; + struct quoting_options *p = xmemdup (o ? o : &default_quoting_options, + sizeof *o); + errno = e; + return p; +} + +/* Get the value of O's quoting style. If O is null, use the default. */ +enum quoting_style +get_quoting_style (struct quoting_options *o) +{ + return (o ? o : &default_quoting_options)->style; +} + +/* In O (or in the default if O is null), + set the value of the quoting style to S. */ +void +set_quoting_style (struct quoting_options *o, enum quoting_style s) +{ + (o ? o : &default_quoting_options)->style = s; +} + +/* In O (or in the default if O is null), + set the value of the quoting options for character C to I. + Return the old value. Currently, the only values defined for I are + 0 (the default) and 1 (which means to quote the character even if + it would not otherwise be quoted). */ +int +set_char_quoting (struct quoting_options *o, char c, int i) +{ + unsigned char uc = c; + unsigned int *p = + (o ? o : &default_quoting_options)->quote_these_too + uc / INT_BITS; + int shift = uc % INT_BITS; + int r = (*p >> shift) & 1; + *p ^= ((i & 1) ^ r) << shift; + return r; +} + +/* MSGID approximates a quotation mark. Return its translation if it + has one; otherwise, return either it or "\"", depending on S. */ +static char const * +gettext_quote (char const *msgid, enum quoting_style s) +{ + char const *translation = _(msgid); + if (translation == msgid && s == clocale_quoting_style) + translation = "\""; + return translation; +} + +/* Place into buffer BUFFER (of size BUFFERSIZE) a quoted version of + argument ARG (of size ARGSIZE), using QUOTING_STYLE and the + non-quoting-style part of O to control quoting. + Terminate the output with a null character, and return the written + size of the output, not counting the terminating null. + If BUFFERSIZE is too small to store the output string, return the + value that would have been returned had BUFFERSIZE been large enough. + If ARGSIZE is SIZE_MAX, use the string length of the argument for ARGSIZE. + + This function acts like quotearg_buffer (BUFFER, BUFFERSIZE, ARG, + ARGSIZE, O), except it uses QUOTING_STYLE instead of the quoting + style specified by O, and O may not be null. */ + +static size_t +quotearg_buffer_restyled (char *buffer, size_t buffersize, + char const *arg, size_t argsize, + enum quoting_style quoting_style, + struct quoting_options const *o) +{ + size_t i; + size_t len = 0; + char const *quote_string = 0; + size_t quote_string_len = 0; + bool backslash_escapes = false; + bool unibyte_locale = MB_CUR_MAX == 1; + +#define STORE(c) \ + do \ + { \ + if (len < buffersize) \ + buffer[len] = (c); \ + len++; \ + } \ + while (0) + + switch (quoting_style) + { + case c_quoting_style: + STORE ('"'); + backslash_escapes = true; + quote_string = "\""; + quote_string_len = 1; + break; + + case escape_quoting_style: + backslash_escapes = true; + break; + + case locale_quoting_style: + case clocale_quoting_style: + { + /* TRANSLATORS: + Get translations for open and closing quotation marks. + + The message catalog should translate "`" to a left + quotation mark suitable for the locale, and similarly for + "'". If the catalog has no translation, + locale_quoting_style quotes `like this', and + clocale_quoting_style quotes "like this". + + For example, an American English Unicode locale should + translate "`" to U+201C (LEFT DOUBLE QUOTATION MARK), and + should translate "'" to U+201D (RIGHT DOUBLE QUOTATION + MARK). A British English Unicode locale should instead + translate these to U+2018 (LEFT SINGLE QUOTATION MARK) and + U+2019 (RIGHT SINGLE QUOTATION MARK), respectively. + + If you don't know what to put here, please see + + and use glyphs suitable for your language. */ + + char const *left = gettext_quote (N_("`"), quoting_style); + char const *right = gettext_quote (N_("'"), quoting_style); + for (quote_string = left; *quote_string; quote_string++) + STORE (*quote_string); + backslash_escapes = true; + quote_string = right; + quote_string_len = strlen (quote_string); + } + break; + + case shell_always_quoting_style: + STORE ('\''); + quote_string = "'"; + quote_string_len = 1; + break; + + default: + break; + } + + for (i = 0; ! (argsize == SIZE_MAX ? arg[i] == '\0' : i == argsize); i++) + { + unsigned char c; + unsigned char esc; + + if (backslash_escapes + && quote_string_len + && i + quote_string_len <= argsize + && memcmp (arg + i, quote_string, quote_string_len) == 0) + STORE ('\\'); + + c = arg[i]; + switch (c) + { + case '\0': + if (backslash_escapes) + { + STORE ('\\'); + STORE ('0'); + STORE ('0'); + c = '0'; + } + break; + + case '?': + switch (quoting_style) + { + case shell_quoting_style: + goto use_shell_always_quoting_style; + + case c_quoting_style: + if (i + 2 < argsize && arg[i + 1] == '?') + switch (arg[i + 2]) + { + case '!': case '\'': + case '(': case ')': case '-': case '/': + case '<': case '=': case '>': + /* Escape the second '?' in what would otherwise be + a trigraph. */ + c = arg[i + 2]; + i += 2; + STORE ('?'); + STORE ('\\'); + STORE ('?'); + break; + + default: + break; + } + break; + + default: + break; + } + break; + + case '\a': esc = 'a'; goto c_escape; + case '\b': esc = 'b'; goto c_escape; + case '\f': esc = 'f'; goto c_escape; + case '\n': esc = 'n'; goto c_and_shell_escape; + case '\r': esc = 'r'; goto c_and_shell_escape; + case '\t': esc = 't'; goto c_and_shell_escape; + case '\v': esc = 'v'; goto c_escape; + case '\\': esc = c; goto c_and_shell_escape; + + c_and_shell_escape: + if (quoting_style == shell_quoting_style) + goto use_shell_always_quoting_style; + c_escape: + if (backslash_escapes) + { + c = esc; + goto store_escape; + } + break; + + case '{': case '}': /* sometimes special if isolated */ + if (! (argsize == SIZE_MAX ? arg[1] == '\0' : argsize == 1)) + break; + /* Fall through. */ + case '#': case '~': + if (i != 0) + break; + /* Fall through. */ + case ' ': + case '!': /* special in bash */ + case '"': case '$': case '&': + case '(': case ')': case '*': case ';': + case '<': + case '=': /* sometimes special in 0th or (with "set -k") later args */ + case '>': case '[': + case '^': /* special in old /bin/sh, e.g. SunOS 4.1.4 */ + case '`': case '|': + /* A shell special character. In theory, '$' and '`' could + be the first bytes of multibyte characters, which means + we should check them with mbrtowc, but in practice this + doesn't happen so it's not worth worrying about. */ + if (quoting_style == shell_quoting_style) + goto use_shell_always_quoting_style; + break; + + case '\'': + switch (quoting_style) + { + case shell_quoting_style: + goto use_shell_always_quoting_style; + + case shell_always_quoting_style: + STORE ('\''); + STORE ('\\'); + STORE ('\''); + break; + + default: + break; + } + break; + + case '%': case '+': case ',': case '-': case '.': case '/': + case '0': case '1': case '2': case '3': case '4': case '5': + case '6': case '7': case '8': case '9': case ':': + case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': + case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': + case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': + case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': + case 'Y': case 'Z': case ']': case '_': case 'a': case 'b': + case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': + case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': + case 'o': case 'p': case 'q': case 'r': case 's': case 't': + case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': + /* These characters don't cause problems, no matter what the + quoting style is. They cannot start multibyte sequences. */ + break; + + default: + /* If we have a multibyte sequence, copy it until we reach + its end, find an error, or come back to the initial shift + state. For C-like styles, if the sequence has + unprintable characters, escape the whole sequence, since + we can't easily escape single characters within it. */ + { + /* Length of multibyte sequence found so far. */ + size_t m; + + bool printable; + + if (unibyte_locale) + { + m = 1; + printable = isprint (c) != 0; + } + else + { + mbstate_t mbstate; + memset (&mbstate, 0, sizeof mbstate); + + m = 0; + printable = true; + if (argsize == SIZE_MAX) + argsize = strlen (arg); + + do + { + wchar_t w; + size_t bytes = mbrtowc (&w, &arg[i + m], + argsize - (i + m), &mbstate); + if (bytes == 0) + break; + else if (bytes == (size_t) -1) + { + printable = false; + break; + } + else if (bytes == (size_t) -2) + { + printable = false; + while (i + m < argsize && arg[i + m]) + m++; + break; + } + else + { + /* Work around a bug with older shells that "see" a '\' + that is really the 2nd byte of a multibyte character. + In practice the problem is limited to ASCII + chars >= '@' that are shell special chars. */ + if ('[' == 0x5b && quoting_style == shell_quoting_style) + { + size_t j; + for (j = 1; j < bytes; j++) + switch (arg[i + m + j]) + { + case '[': case '\\': case '^': + case '`': case '|': + goto use_shell_always_quoting_style; + + default: + break; + } + } + + if (! iswprint (w)) + printable = false; + m += bytes; + } + } + while (! mbsinit (&mbstate)); + } + + if (1 < m || (backslash_escapes && ! printable)) + { + /* Output a multibyte sequence, or an escaped + unprintable unibyte character. */ + size_t ilim = i + m; + + for (;;) + { + if (backslash_escapes && ! printable) + { + STORE ('\\'); + STORE ('0' + (c >> 6)); + STORE ('0' + ((c >> 3) & 7)); + c = '0' + (c & 7); + } + if (ilim <= i + 1) + break; + STORE (c); + c = arg[++i]; + } + + goto store_c; + } + } + } + + if (! (backslash_escapes + && o->quote_these_too[c / INT_BITS] & (1 << (c % INT_BITS)))) + goto store_c; + + store_escape: + STORE ('\\'); + + store_c: + STORE (c); + } + + if (i == 0 && quoting_style == shell_quoting_style) + goto use_shell_always_quoting_style; + + if (quote_string) + for (; *quote_string; quote_string++) + STORE (*quote_string); + + if (len < buffersize) + buffer[len] = '\0'; + return len; + + use_shell_always_quoting_style: + return quotearg_buffer_restyled (buffer, buffersize, arg, argsize, + shell_always_quoting_style, o); +} + +/* Place into buffer BUFFER (of size BUFFERSIZE) a quoted version of + argument ARG (of size ARGSIZE), using O to control quoting. + If O is null, use the default. + Terminate the output with a null character, and return the written + size of the output, not counting the terminating null. + If BUFFERSIZE is too small to store the output string, return the + value that would have been returned had BUFFERSIZE been large enough. + If ARGSIZE is SIZE_MAX, use the string length of the argument for + ARGSIZE. */ +size_t +quotearg_buffer (char *buffer, size_t buffersize, + char const *arg, size_t argsize, + struct quoting_options const *o) +{ + struct quoting_options const *p = o ? o : &default_quoting_options; + int e = errno; + size_t r = quotearg_buffer_restyled (buffer, buffersize, arg, argsize, + p->style, p); + errno = e; + return r; +} + +/* Like quotearg_buffer (..., ARG, ARGSIZE, O), except return newly + allocated storage containing the quoted string. */ +char * +quotearg_alloc (char const *arg, size_t argsize, + struct quoting_options const *o) +{ + int e = errno; + size_t bufsize = quotearg_buffer (0, 0, arg, argsize, o) + 1; + char *buf = xcharalloc (bufsize); + quotearg_buffer (buf, bufsize, arg, argsize, o); + errno = e; + return buf; +} + +/* A storage slot with size and pointer to a value. */ +struct slotvec +{ + size_t size; + char *val; +}; + +/* Preallocate a slot 0 buffer, so that the caller can always quote + one small component of a "memory exhausted" message in slot 0. */ +static char slot0[256]; +static unsigned int nslots = 1; +static struct slotvec slotvec0 = {sizeof slot0, slot0}; +static struct slotvec *slotvec = &slotvec0; + +void +quotearg_free (void) +{ + struct slotvec *sv = slotvec; + unsigned int i; + for (i = 1; i < nslots; i++) + free (sv[i].val); + if (sv[0].val != slot0) + { + free (sv[0].val); + slotvec0.size = sizeof slot0; + slotvec0.val = slot0; + } + if (sv != &slotvec0) + { + free (sv); + slotvec = &slotvec0; + } + nslots = 1; +} + +/* Use storage slot N to return a quoted version of argument ARG. + ARG is of size ARGSIZE, but if that is SIZE_MAX, ARG is a + null-terminated string. + OPTIONS specifies the quoting options. + The returned value points to static storage that can be + reused by the next call to this function with the same value of N. + N must be nonnegative. N is deliberately declared with type "int" + to allow for future extensions (using negative values). */ +static char * +quotearg_n_options (int n, char const *arg, size_t argsize, + struct quoting_options const *options) +{ + int e = errno; + + unsigned int n0 = n; + struct slotvec *sv = slotvec; + + if (n < 0) + abort (); + + if (nslots <= n0) + { + /* FIXME: technically, the type of n1 should be `unsigned int', + but that evokes an unsuppressible warning from gcc-4.0.1 and + older. If gcc ever provides an option to suppress that warning, + revert to the original type, so that the test in xalloc_oversized + is once again performed only at compile time. */ + size_t n1 = n0 + 1; + bool preallocated = (sv == &slotvec0); + + if (xalloc_oversized (n1, sizeof *sv)) + xalloc_die (); + + slotvec = sv = xrealloc (preallocated ? NULL : sv, n1 * sizeof *sv); + if (preallocated) + *sv = slotvec0; + memset (sv + nslots, 0, (n1 - nslots) * sizeof *sv); + nslots = n1; + } + + { + size_t size = sv[n].size; + char *val = sv[n].val; + size_t qsize = quotearg_buffer (val, size, arg, argsize, options); + + if (size <= qsize) + { + sv[n].size = size = qsize + 1; + if (val != slot0) + free (val); + sv[n].val = val = xcharalloc (size); + quotearg_buffer (val, size, arg, argsize, options); + } + + errno = e; + return val; + } +} + +char * +quotearg_n (int n, char const *arg) +{ + return quotearg_n_options (n, arg, SIZE_MAX, &default_quoting_options); +} + +char * +quotearg (char const *arg) +{ + return quotearg_n (0, arg); +} + +/* Return quoting options for STYLE, with no extra quoting. */ +static struct quoting_options +quoting_options_from_style (enum quoting_style style) +{ + struct quoting_options o; + o.style = style; + memset (o.quote_these_too, 0, sizeof o.quote_these_too); + return o; +} + +char * +quotearg_n_style (int n, enum quoting_style s, char const *arg) +{ + struct quoting_options const o = quoting_options_from_style (s); + return quotearg_n_options (n, arg, SIZE_MAX, &o); +} + +char * +quotearg_n_style_mem (int n, enum quoting_style s, + char const *arg, size_t argsize) +{ + struct quoting_options const o = quoting_options_from_style (s); + return quotearg_n_options (n, arg, argsize, &o); +} + +char * +quotearg_style (enum quoting_style s, char const *arg) +{ + return quotearg_n_style (0, s, arg); +} + +char * +quotearg_char (char const *arg, char ch) +{ + struct quoting_options options; + options = default_quoting_options; + set_char_quoting (&options, ch, 1); + return quotearg_n_options (0, arg, SIZE_MAX, &options); +} + +char * +quotearg_colon (char const *arg) +{ + return quotearg_char (arg, ':'); +} diff --git a/src/bin/findutils/gnulib/lib/quotearg.h b/src/bin/findutils/gnulib/lib/quotearg.h new file mode 100644 index 0000000000..d11d059fb3 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/quotearg.h @@ -0,0 +1,139 @@ +/* quotearg.h - quote arguments for output + + Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2006 Free + Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert */ + +#ifndef QUOTEARG_H_ +# define QUOTEARG_H_ 1 + +# include + +/* Basic quoting styles. */ +enum quoting_style + { + /* Output names as-is (ls --quoting-style=literal). */ + literal_quoting_style, + + /* Quote names for the shell if they contain shell metacharacters + or would cause ambiguous output (ls --quoting-style=shell). */ + shell_quoting_style, + + /* Quote names for the shell, even if they would normally not + require quoting (ls --quoting-style=shell-always). */ + shell_always_quoting_style, + + /* Quote names as for a C language string (ls --quoting-style=c). */ + c_quoting_style, + + /* Like c_quoting_style except omit the surrounding double-quote + characters (ls --quoting-style=escape). */ + escape_quoting_style, + + /* Like clocale_quoting_style, but quote `like this' instead of + "like this" in the default C locale (ls --quoting-style=locale). */ + locale_quoting_style, + + /* Like c_quoting_style except use quotation marks appropriate for + the locale (ls --quoting-style=clocale). */ + clocale_quoting_style + }; + +/* For now, --quoting-style=literal is the default, but this may change. */ +# ifndef DEFAULT_QUOTING_STYLE +# define DEFAULT_QUOTING_STYLE literal_quoting_style +# endif + +/* Names of quoting styles and their corresponding values. */ +extern char const *const quoting_style_args[]; +extern enum quoting_style const quoting_style_vals[]; + +struct quoting_options; + +/* The functions listed below set and use a hidden variable + that contains the default quoting style options. */ + +/* Allocate a new set of quoting options, with contents initially identical + to O if O is not null, or to the default if O is null. + It is the caller's responsibility to free the result. */ +struct quoting_options *clone_quoting_options (struct quoting_options *o); + +/* Get the value of O's quoting style. If O is null, use the default. */ +enum quoting_style get_quoting_style (struct quoting_options *o); + +/* In O (or in the default if O is null), + set the value of the quoting style to S. */ +void set_quoting_style (struct quoting_options *o, enum quoting_style s); + +/* In O (or in the default if O is null), + set the value of the quoting options for character C to I. + Return the old value. Currently, the only values defined for I are + 0 (the default) and 1 (which means to quote the character even if + it would not otherwise be quoted). */ +int set_char_quoting (struct quoting_options *o, char c, int i); + +/* Place into buffer BUFFER (of size BUFFERSIZE) a quoted version of + argument ARG (of size ARGSIZE), using O to control quoting. + If O is null, use the default. + Terminate the output with a null character, and return the written + size of the output, not counting the terminating null. + If BUFFERSIZE is too small to store the output string, return the + value that would have been returned had BUFFERSIZE been large enough. + If ARGSIZE is -1, use the string length of the argument for ARGSIZE. */ +size_t quotearg_buffer (char *buffer, size_t buffersize, + char const *arg, size_t argsize, + struct quoting_options const *o); + +/* Like quotearg_buffer, except return the result in a newly allocated + buffer. It is the caller's responsibility to free the result. */ +char *quotearg_alloc (char const *arg, size_t argsize, + struct quoting_options const *o); + +/* Use storage slot N to return a quoted version of the string ARG. + Use the default quoting options. + The returned value points to static storage that can be + reused by the next call to this function with the same value of N. + N must be nonnegative. */ +char *quotearg_n (int n, char const *arg); + +/* Equivalent to quotearg_n (0, ARG). */ +char *quotearg (char const *arg); + +/* Use style S and storage slot N to return a quoted version of the string ARG. + This is like quotearg_n (N, ARG), except that it uses S with no other + options to specify the quoting method. */ +char *quotearg_n_style (int n, enum quoting_style s, char const *arg); + +/* Use style S and storage slot N to return a quoted version of the + argument ARG of size ARGSIZE. This is like quotearg_n_style + (N, S, ARG), except it can quote null bytes. */ +char *quotearg_n_style_mem (int n, enum quoting_style s, + char const *arg, size_t argsize); + +/* Equivalent to quotearg_n_style (0, S, ARG). */ +char *quotearg_style (enum quoting_style s, char const *arg); + +/* Like quotearg (ARG), except also quote any instances of CH. */ +char *quotearg_char (char const *arg, char ch); + +/* Equivalent to quotearg_char (ARG, ':'). */ +char *quotearg_colon (char const *arg); + +/* Free any dynamically allocated memory. */ +void quotearg_free (void); + +#endif /* !QUOTEARG_H_ */ diff --git a/src/bin/findutils/gnulib/lib/readlink.c b/src/bin/findutils/gnulib/lib/readlink.c new file mode 100644 index 0000000000..5cccdc962a --- /dev/null +++ b/src/bin/findutils/gnulib/lib/readlink.c @@ -0,0 +1,49 @@ +/* Stub for readlink(). + Copyright (C) 2003-2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +/* Specification. */ +#include + +#include +#include +#include +#include + +#if !HAVE_READLINK + +/* readlink() substitute for systems that don't have a readlink() function, + such as DJGPP 2.03 and mingw32. */ + +/* The official POSIX return type of readlink() is ssize_t, but since here + we have no declaration in a public header file, we use 'int' as return + type. */ + +int +readlink (const char *path, char *buf, size_t bufsize) +{ + struct stat statbuf; + + /* In general we should use lstat() here, not stat(). But on platforms + without symbolic links lstat() - if it exists - would be equivalent to + stat(), therefore we can use stat(). This saves us a configure check. */ + if (stat (path, &statbuf) >= 0) + errno = EINVAL; + return -1; +} + +#endif diff --git a/src/bin/findutils/gnulib/lib/realloc.c b/src/bin/findutils/gnulib/lib/realloc.c new file mode 100644 index 0000000000..b61c2ca829 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/realloc.c @@ -0,0 +1,87 @@ +/* realloc() function that is glibc compatible. + + Copyright (C) 1997, 2003, 2004, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering and Bruno Haible */ + +#include + +/* Only the AC_FUNC_REALLOC macro defines 'realloc' already in config.h. */ +#ifdef realloc +# define NEED_REALLOC_GNU 1 +#endif + +/* Infer the properties of the system's malloc function. + Only the AC_FUNC_MALLOC macro defines 'malloc' already in config.h. */ +#if GNULIB_MALLOC_GNU && !defined malloc +# define SYSTEM_MALLOC_GLIBC_COMPATIBLE 1 +#endif + +/* Below we want to call the system's malloc and realloc. + Undefine the symbols here so that including provides a + declaration of malloc(), not of rpl_malloc(), and likewise for realloc. */ +#undef malloc +#undef realloc + +/* Specification. */ +#include + +#include + +/* Below we want to call the system's malloc and realloc. + Undefine the symbols, if they were defined by gnulib's + replacement. */ +#undef malloc +#undef realloc + +/* Change the size of an allocated block of memory P to N bytes, + with error checking. If N is zero, change it to 1. If P is NULL, + use malloc. */ + +void * +rpl_realloc (void *p, size_t n) +{ + void *result; + +#if NEED_REALLOC_GNU + if (n == 0) + { + n = 1; + + /* In theory realloc might fail, so don't rely on it to free. */ + free (p); + p = NULL; + } +#endif + + if (p == NULL) + { +#if GNULIB_REALLOC_GNU && !NEED_REALLOC_GNU && !SYSTEM_MALLOC_GLIBC_COMPATIBLE + if (n == 0) + n = 1; +#endif + result = malloc (n); + } + else + result = realloc (p, n); + +#if !HAVE_REALLOC_POSIX + if (result == NULL) + errno = ENOMEM; +#endif + + return result; +} diff --git a/src/bin/findutils/gnulib/lib/regcomp.c b/src/bin/findutils/gnulib/lib/regcomp.c new file mode 100644 index 0000000000..8827e03c95 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/regcomp.c @@ -0,0 +1,3832 @@ +/* Extended regular expression matching and search library. + Copyright (C) 2002,2003,2004,2005,2006,2007 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Isamu Hasegawa . + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +static reg_errcode_t re_compile_internal (regex_t *preg, const char * pattern, + size_t length, reg_syntax_t syntax); +static void re_compile_fastmap_iter (regex_t *bufp, + const re_dfastate_t *init_state, + char *fastmap); +static reg_errcode_t init_dfa (re_dfa_t *dfa, size_t pat_len); +#ifdef RE_ENABLE_I18N +static void free_charset (re_charset_t *cset); +#endif /* RE_ENABLE_I18N */ +static void free_workarea_compile (regex_t *preg); +static reg_errcode_t create_initial_state (re_dfa_t *dfa); +#ifdef RE_ENABLE_I18N +static void optimize_utf8 (re_dfa_t *dfa); +#endif +static reg_errcode_t analyze (regex_t *preg); +static reg_errcode_t preorder (bin_tree_t *root, + reg_errcode_t (fn (void *, bin_tree_t *)), + void *extra); +static reg_errcode_t postorder (bin_tree_t *root, + reg_errcode_t (fn (void *, bin_tree_t *)), + void *extra); +static reg_errcode_t optimize_subexps (void *extra, bin_tree_t *node); +static reg_errcode_t lower_subexps (void *extra, bin_tree_t *node); +static bin_tree_t *lower_subexp (reg_errcode_t *err, regex_t *preg, + bin_tree_t *node); +static reg_errcode_t calc_first (void *extra, bin_tree_t *node); +static reg_errcode_t calc_next (void *extra, bin_tree_t *node); +static reg_errcode_t link_nfa_nodes (void *extra, bin_tree_t *node); +static Idx duplicate_node (re_dfa_t *dfa, Idx org_idx, unsigned int constraint); +static Idx search_duplicated_node (const re_dfa_t *dfa, Idx org_node, + unsigned int constraint); +static reg_errcode_t calc_eclosure (re_dfa_t *dfa); +static reg_errcode_t calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa, + Idx node, bool root); +static reg_errcode_t calc_inveclosure (re_dfa_t *dfa); +static Idx fetch_number (re_string_t *input, re_token_t *token, + reg_syntax_t syntax); +static int peek_token (re_token_t *token, re_string_t *input, + reg_syntax_t syntax) internal_function; +static bin_tree_t *parse (re_string_t *regexp, regex_t *preg, + reg_syntax_t syntax, reg_errcode_t *err); +static bin_tree_t *parse_reg_exp (re_string_t *regexp, regex_t *preg, + re_token_t *token, reg_syntax_t syntax, + Idx nest, reg_errcode_t *err); +static bin_tree_t *parse_branch (re_string_t *regexp, regex_t *preg, + re_token_t *token, reg_syntax_t syntax, + Idx nest, reg_errcode_t *err); +static bin_tree_t *parse_expression (re_string_t *regexp, regex_t *preg, + re_token_t *token, reg_syntax_t syntax, + Idx nest, reg_errcode_t *err); +static bin_tree_t *parse_sub_exp (re_string_t *regexp, regex_t *preg, + re_token_t *token, reg_syntax_t syntax, + Idx nest, reg_errcode_t *err); +static bin_tree_t *parse_dup_op (bin_tree_t *dup_elem, re_string_t *regexp, + re_dfa_t *dfa, re_token_t *token, + reg_syntax_t syntax, reg_errcode_t *err); +static bin_tree_t *parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, + re_token_t *token, reg_syntax_t syntax, + reg_errcode_t *err); +static reg_errcode_t parse_bracket_element (bracket_elem_t *elem, + re_string_t *regexp, + re_token_t *token, int token_len, + re_dfa_t *dfa, + reg_syntax_t syntax, + bool accept_hyphen); +static reg_errcode_t parse_bracket_symbol (bracket_elem_t *elem, + re_string_t *regexp, + re_token_t *token); +#ifdef RE_ENABLE_I18N +static reg_errcode_t build_equiv_class (bitset_t sbcset, + re_charset_t *mbcset, + Idx *equiv_class_alloc, + const unsigned char *name); +static reg_errcode_t build_charclass (RE_TRANSLATE_TYPE trans, + bitset_t sbcset, + re_charset_t *mbcset, + Idx *char_class_alloc, + const unsigned char *class_name, + reg_syntax_t syntax); +#else /* not RE_ENABLE_I18N */ +static reg_errcode_t build_equiv_class (bitset_t sbcset, + const unsigned char *name); +static reg_errcode_t build_charclass (RE_TRANSLATE_TYPE trans, + bitset_t sbcset, + const unsigned char *class_name, + reg_syntax_t syntax); +#endif /* not RE_ENABLE_I18N */ +static bin_tree_t *build_charclass_op (re_dfa_t *dfa, + RE_TRANSLATE_TYPE trans, + const unsigned char *class_name, + const unsigned char *extra, + bool non_match, reg_errcode_t *err); +static bin_tree_t *create_tree (re_dfa_t *dfa, + bin_tree_t *left, bin_tree_t *right, + re_token_type_t type); +static bin_tree_t *create_token_tree (re_dfa_t *dfa, + bin_tree_t *left, bin_tree_t *right, + const re_token_t *token); +static bin_tree_t *duplicate_tree (const bin_tree_t *src, re_dfa_t *dfa); +static void free_token (re_token_t *node); +static reg_errcode_t free_tree (void *extra, bin_tree_t *node); +static reg_errcode_t mark_opt_subexp (void *extra, bin_tree_t *node); + +/* This table gives an error message for each of the error codes listed + in regex.h. Obviously the order here has to be same as there. + POSIX doesn't require that we do anything for REG_NOERROR, + but why not be nice? */ + +static const char __re_error_msgid[] = + { +#define REG_NOERROR_IDX 0 + gettext_noop ("Success") /* REG_NOERROR */ + "\0" +#define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success") + gettext_noop ("No match") /* REG_NOMATCH */ + "\0" +#define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match") + gettext_noop ("Invalid regular expression") /* REG_BADPAT */ + "\0" +#define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression") + gettext_noop ("Invalid collation character") /* REG_ECOLLATE */ + "\0" +#define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character") + gettext_noop ("Invalid character class name") /* REG_ECTYPE */ + "\0" +#define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name") + gettext_noop ("Trailing backslash") /* REG_EESCAPE */ + "\0" +#define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash") + gettext_noop ("Invalid back reference") /* REG_ESUBREG */ + "\0" +#define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference") + gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */ + "\0" +#define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^") + gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */ + "\0" +#define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(") + gettext_noop ("Unmatched \\{") /* REG_EBRACE */ + "\0" +#define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{") + gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */ + "\0" +#define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}") + gettext_noop ("Invalid range end") /* REG_ERANGE */ + "\0" +#define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end") + gettext_noop ("Memory exhausted") /* REG_ESPACE */ + "\0" +#define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted") + gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */ + "\0" +#define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression") + gettext_noop ("Premature end of regular expression") /* REG_EEND */ + "\0" +#define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression") + gettext_noop ("Regular expression too big") /* REG_ESIZE */ + "\0" +#define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big") + gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */ + }; + +static const size_t __re_error_msgid_idx[] = + { + REG_NOERROR_IDX, + REG_NOMATCH_IDX, + REG_BADPAT_IDX, + REG_ECOLLATE_IDX, + REG_ECTYPE_IDX, + REG_EESCAPE_IDX, + REG_ESUBREG_IDX, + REG_EBRACK_IDX, + REG_EPAREN_IDX, + REG_EBRACE_IDX, + REG_BADBR_IDX, + REG_ERANGE_IDX, + REG_ESPACE_IDX, + REG_BADRPT_IDX, + REG_EEND_IDX, + REG_ESIZE_IDX, + REG_ERPAREN_IDX + }; + +/* Entry points for GNU code. */ + +/* re_compile_pattern is the GNU regular expression compiler: it + compiles PATTERN (of length LENGTH) and puts the result in BUFP. + Returns 0 if the pattern was valid, otherwise an error string. + + Assumes the `allocated' (and perhaps `buffer') and `translate' fields + are set in BUFP on entry. */ + +#ifdef _LIBC +const char * +re_compile_pattern (pattern, length, bufp) + const char *pattern; + size_t length; + struct re_pattern_buffer *bufp; +#else /* size_t might promote */ +const char * +re_compile_pattern (const char *pattern, size_t length, + struct re_pattern_buffer *bufp) +#endif +{ + reg_errcode_t ret; + + /* And GNU code determines whether or not to get register information + by passing null for the REGS argument to re_match, etc., not by + setting no_sub, unless RE_NO_SUB is set. */ + bufp->no_sub = !!(re_syntax_options & RE_NO_SUB); + + /* Match anchors at newline. */ + bufp->newline_anchor = 1; + + ret = re_compile_internal (bufp, pattern, length, re_syntax_options); + + if (!ret) + return NULL; + return gettext (__re_error_msgid + __re_error_msgid_idx[(int) ret]); +} +#ifdef _LIBC +weak_alias (__re_compile_pattern, re_compile_pattern) +#endif + +/* Set by `re_set_syntax' to the current regexp syntax to recognize. Can + also be assigned to arbitrarily: each pattern buffer stores its own + syntax, so it can be changed between regex compilations. */ +/* This has no initializer because initialized variables in Emacs + become read-only after dumping. */ +reg_syntax_t re_syntax_options; + + +/* Specify the precise syntax of regexps for compilation. This provides + for compatibility for various utilities which historically have + different, incompatible syntaxes. + + The argument SYNTAX is a bit mask comprised of the various bits + defined in regex.h. We return the old syntax. */ + +reg_syntax_t +re_set_syntax (syntax) + reg_syntax_t syntax; +{ + reg_syntax_t ret = re_syntax_options; + + re_syntax_options = syntax; + return ret; +} +#ifdef _LIBC +weak_alias (__re_set_syntax, re_set_syntax) +#endif + +int +re_compile_fastmap (bufp) + struct re_pattern_buffer *bufp; +{ + re_dfa_t *dfa = (re_dfa_t *) bufp->buffer; + char *fastmap = bufp->fastmap; + + memset (fastmap, '\0', sizeof (char) * SBC_MAX); + re_compile_fastmap_iter (bufp, dfa->init_state, fastmap); + if (dfa->init_state != dfa->init_state_word) + re_compile_fastmap_iter (bufp, dfa->init_state_word, fastmap); + if (dfa->init_state != dfa->init_state_nl) + re_compile_fastmap_iter (bufp, dfa->init_state_nl, fastmap); + if (dfa->init_state != dfa->init_state_begbuf) + re_compile_fastmap_iter (bufp, dfa->init_state_begbuf, fastmap); + bufp->fastmap_accurate = 1; + return 0; +} +#ifdef _LIBC +weak_alias (__re_compile_fastmap, re_compile_fastmap) +#endif + +static inline void +__attribute ((always_inline)) +re_set_fastmap (char *fastmap, bool icase, int ch) +{ + fastmap[ch] = 1; + if (icase) + fastmap[tolower (ch)] = 1; +} + +/* Helper function for re_compile_fastmap. + Compile fastmap for the initial_state INIT_STATE. */ + +static void +re_compile_fastmap_iter (regex_t *bufp, const re_dfastate_t *init_state, + char *fastmap) +{ + re_dfa_t *dfa = (re_dfa_t *) bufp->buffer; + Idx node_cnt; + bool icase = (dfa->mb_cur_max == 1 && (bufp->syntax & RE_ICASE)); + for (node_cnt = 0; node_cnt < init_state->nodes.nelem; ++node_cnt) + { + Idx node = init_state->nodes.elems[node_cnt]; + re_token_type_t type = dfa->nodes[node].type; + + if (type == CHARACTER) + { + re_set_fastmap (fastmap, icase, dfa->nodes[node].opr.c); +#ifdef RE_ENABLE_I18N + if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1) + { + unsigned char buf[MB_LEN_MAX]; + unsigned char *p; + wchar_t wc; + mbstate_t state; + + p = buf; + *p++ = dfa->nodes[node].opr.c; + while (++node < dfa->nodes_len + && dfa->nodes[node].type == CHARACTER + && dfa->nodes[node].mb_partial) + *p++ = dfa->nodes[node].opr.c; + memset (&state, '\0', sizeof (state)); + if (mbrtowc (&wc, (const char *) buf, p - buf, + &state) == p - buf + && (__wcrtomb ((char *) buf, towlower (wc), &state) + != (size_t) -1)) + re_set_fastmap (fastmap, false, buf[0]); + } +#endif + } + else if (type == SIMPLE_BRACKET) + { + int i, ch; + for (i = 0, ch = 0; i < BITSET_WORDS; ++i) + { + int j; + bitset_word_t w = dfa->nodes[node].opr.sbcset[i]; + for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch) + if (w & ((bitset_word_t) 1 << j)) + re_set_fastmap (fastmap, icase, ch); + } + } +#ifdef RE_ENABLE_I18N + else if (type == COMPLEX_BRACKET) + { + Idx i; + re_charset_t *cset = dfa->nodes[node].opr.mbcset; + if (cset->non_match || cset->ncoll_syms || cset->nequiv_classes + || cset->nranges || cset->nchar_classes) + { +# ifdef _LIBC + if (_NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES) != 0) + { + /* In this case we want to catch the bytes which are + the first byte of any collation elements. + e.g. In da_DK, we want to catch 'a' since "aa" + is a valid collation element, and don't catch + 'b' since 'b' is the only collation element + which starts from 'b'. */ + const int32_t *table = (const int32_t *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB); + for (i = 0; i < SBC_MAX; ++i) + if (table[i] < 0) + re_set_fastmap (fastmap, icase, i); + } +# else + if (dfa->mb_cur_max > 1) + for (i = 0; i < SBC_MAX; ++i) + if (__btowc (i) == WEOF) + re_set_fastmap (fastmap, icase, i); +# endif /* not _LIBC */ + } + for (i = 0; i < cset->nmbchars; ++i) + { + char buf[256]; + mbstate_t state; + memset (&state, '\0', sizeof (state)); + if (__wcrtomb (buf, cset->mbchars[i], &state) != (size_t) -1) + re_set_fastmap (fastmap, icase, *(unsigned char *) buf); + if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1) + { + if (__wcrtomb (buf, towlower (cset->mbchars[i]), &state) + != (size_t) -1) + re_set_fastmap (fastmap, false, *(unsigned char *) buf); + } + } + } +#endif /* RE_ENABLE_I18N */ + else if (type == OP_PERIOD +#ifdef RE_ENABLE_I18N + || type == OP_UTF8_PERIOD +#endif /* RE_ENABLE_I18N */ + || type == END_OF_RE) + { + memset (fastmap, '\1', sizeof (char) * SBC_MAX); + if (type == END_OF_RE) + bufp->can_be_null = 1; + return; + } + } +} + +/* Entry point for POSIX code. */ +/* regcomp takes a regular expression as a string and compiles it. + + PREG is a regex_t *. We do not expect any fields to be initialized, + since POSIX says we shouldn't. Thus, we set + + `buffer' to the compiled pattern; + `used' to the length of the compiled pattern; + `syntax' to RE_SYNTAX_POSIX_EXTENDED if the + REG_EXTENDED bit in CFLAGS is set; otherwise, to + RE_SYNTAX_POSIX_BASIC; + `newline_anchor' to REG_NEWLINE being set in CFLAGS; + `fastmap' to an allocated space for the fastmap; + `fastmap_accurate' to zero; + `re_nsub' to the number of subexpressions in PATTERN. + + PATTERN is the address of the pattern string. + + CFLAGS is a series of bits which affect compilation. + + If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we + use POSIX basic syntax. + + If REG_NEWLINE is set, then . and [^...] don't match newline. + Also, regexec will try a match beginning after every newline. + + If REG_ICASE is set, then we considers upper- and lowercase + versions of letters to be equivalent when matching. + + If REG_NOSUB is set, then when PREG is passed to regexec, that + routine will report only success or failure, and nothing about the + registers. + + It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for + the return codes and their meanings.) */ + +int +regcomp (preg, pattern, cflags) + regex_t *_Restrict_ preg; + const char *_Restrict_ pattern; + int cflags; +{ + reg_errcode_t ret; + reg_syntax_t syntax = ((cflags & REG_EXTENDED) ? RE_SYNTAX_POSIX_EXTENDED + : RE_SYNTAX_POSIX_BASIC); + + preg->buffer = NULL; + preg->allocated = 0; + preg->used = 0; + + /* Try to allocate space for the fastmap. */ + preg->fastmap = re_malloc (char, SBC_MAX); + if (BE (preg->fastmap == NULL, 0)) + return REG_ESPACE; + + syntax |= (cflags & REG_ICASE) ? RE_ICASE : 0; + + /* If REG_NEWLINE is set, newlines are treated differently. */ + if (cflags & REG_NEWLINE) + { /* REG_NEWLINE implies neither . nor [^...] match newline. */ + syntax &= ~RE_DOT_NEWLINE; + syntax |= RE_HAT_LISTS_NOT_NEWLINE; + /* It also changes the matching behavior. */ + preg->newline_anchor = 1; + } + else + preg->newline_anchor = 0; + preg->no_sub = !!(cflags & REG_NOSUB); + preg->translate = NULL; + + ret = re_compile_internal (preg, pattern, strlen (pattern), syntax); + + /* POSIX doesn't distinguish between an unmatched open-group and an + unmatched close-group: both are REG_EPAREN. */ + if (ret == REG_ERPAREN) + ret = REG_EPAREN; + + /* We have already checked preg->fastmap != NULL. */ + if (BE (ret == REG_NOERROR, 1)) + /* Compute the fastmap now, since regexec cannot modify the pattern + buffer. This function never fails in this implementation. */ + (void) re_compile_fastmap (preg); + else + { + /* Some error occurred while compiling the expression. */ + re_free (preg->fastmap); + preg->fastmap = NULL; + } + + return (int) ret; +} +#ifdef _LIBC +weak_alias (__regcomp, regcomp) +#endif + +/* Returns a message corresponding to an error code, ERRCODE, returned + from either regcomp or regexec. We don't use PREG here. */ + +#ifdef _LIBC +size_t +regerror (errcode, preg, errbuf, errbuf_size) + int errcode; + const regex_t *_Restrict_ preg; + char *_Restrict_ errbuf; + size_t errbuf_size; +#else /* size_t might promote */ +size_t +regerror (int errcode, const regex_t *_Restrict_ preg, + char *_Restrict_ errbuf, size_t errbuf_size) +#endif +{ + const char *msg; + size_t msg_size; + + if (BE (errcode < 0 + || errcode >= (int) (sizeof (__re_error_msgid_idx) + / sizeof (__re_error_msgid_idx[0])), 0)) + /* Only error codes returned by the rest of the code should be passed + to this routine. If we are given anything else, or if other regex + code generates an invalid error code, then the program has a bug. + Dump core so we can fix it. */ + abort (); + + msg = gettext (__re_error_msgid + __re_error_msgid_idx[errcode]); + + msg_size = strlen (msg) + 1; /* Includes the null. */ + + if (BE (errbuf_size != 0, 1)) + { + size_t cpy_size = msg_size; + if (BE (msg_size > errbuf_size, 0)) + { + cpy_size = errbuf_size - 1; + errbuf[cpy_size] = '\0'; + } + memcpy (errbuf, msg, cpy_size); + } + + return msg_size; +} +#ifdef _LIBC +weak_alias (__regerror, regerror) +#endif + + +#ifdef RE_ENABLE_I18N +/* This static array is used for the map to single-byte characters when + UTF-8 is used. Otherwise we would allocate memory just to initialize + it the same all the time. UTF-8 is the preferred encoding so this is + a worthwhile optimization. */ +static const bitset_t utf8_sb_map = +{ + /* Set the first 128 bits. */ +# if 4 * BITSET_WORD_BITS < ASCII_CHARS +# error "bitset_word_t is narrower than 32 bits" +# elif 3 * BITSET_WORD_BITS < ASCII_CHARS + BITSET_WORD_MAX, BITSET_WORD_MAX, BITSET_WORD_MAX, +# elif 2 * BITSET_WORD_BITS < ASCII_CHARS + BITSET_WORD_MAX, BITSET_WORD_MAX, +# elif 1 * BITSET_WORD_BITS < ASCII_CHARS + BITSET_WORD_MAX, +# endif + (BITSET_WORD_MAX + >> (SBC_MAX % BITSET_WORD_BITS == 0 + ? 0 + : BITSET_WORD_BITS - SBC_MAX % BITSET_WORD_BITS)) +}; +#endif + + +static void +free_dfa_content (re_dfa_t *dfa) +{ + Idx i, j; + + if (dfa->nodes) + for (i = 0; i < dfa->nodes_len; ++i) + free_token (dfa->nodes + i); + re_free (dfa->nexts); + for (i = 0; i < dfa->nodes_len; ++i) + { + if (dfa->eclosures != NULL) + re_node_set_free (dfa->eclosures + i); + if (dfa->inveclosures != NULL) + re_node_set_free (dfa->inveclosures + i); + if (dfa->edests != NULL) + re_node_set_free (dfa->edests + i); + } + re_free (dfa->edests); + re_free (dfa->eclosures); + re_free (dfa->inveclosures); + re_free (dfa->nodes); + + if (dfa->state_table) + for (i = 0; i <= dfa->state_hash_mask; ++i) + { + struct re_state_table_entry *entry = dfa->state_table + i; + for (j = 0; j < entry->num; ++j) + { + re_dfastate_t *state = entry->array[j]; + free_state (state); + } + re_free (entry->array); + } + re_free (dfa->state_table); +#ifdef RE_ENABLE_I18N + if (dfa->sb_char != utf8_sb_map) + re_free (dfa->sb_char); +#endif + re_free (dfa->subexp_map); +#ifdef DEBUG + re_free (dfa->re_str); +#endif + + re_free (dfa); +} + + +/* Free dynamically allocated space used by PREG. */ + +void +regfree (preg) + regex_t *preg; +{ + re_dfa_t *dfa = (re_dfa_t *) preg->buffer; + if (BE (dfa != NULL, 1)) + free_dfa_content (dfa); + preg->buffer = NULL; + preg->allocated = 0; + + re_free (preg->fastmap); + preg->fastmap = NULL; + + re_free (preg->translate); + preg->translate = NULL; +} +#ifdef _LIBC +weak_alias (__regfree, regfree) +#endif + +/* Entry points compatible with 4.2 BSD regex library. We don't define + them unless specifically requested. */ + +#if defined _REGEX_RE_COMP || defined _LIBC + +/* BSD has one and only one pattern buffer. */ +static struct re_pattern_buffer re_comp_buf; + +char * +# ifdef _LIBC +/* Make these definitions weak in libc, so POSIX programs can redefine + these names if they don't use our functions, and still use + regcomp/regexec above without link errors. */ +weak_function +# endif +re_comp (s) + const char *s; +{ + reg_errcode_t ret; + char *fastmap; + + if (!s) + { + if (!re_comp_buf.buffer) + return gettext ("No previous regular expression"); + return 0; + } + + if (re_comp_buf.buffer) + { + fastmap = re_comp_buf.fastmap; + re_comp_buf.fastmap = NULL; + __regfree (&re_comp_buf); + memset (&re_comp_buf, '\0', sizeof (re_comp_buf)); + re_comp_buf.fastmap = fastmap; + } + + if (re_comp_buf.fastmap == NULL) + { + re_comp_buf.fastmap = (char *) malloc (SBC_MAX); + if (re_comp_buf.fastmap == NULL) + return (char *) gettext (__re_error_msgid + + __re_error_msgid_idx[(int) REG_ESPACE]); + } + + /* Since `re_exec' always passes NULL for the `regs' argument, we + don't need to initialize the pattern buffer fields which affect it. */ + + /* Match anchors at newlines. */ + re_comp_buf.newline_anchor = 1; + + ret = re_compile_internal (&re_comp_buf, s, strlen (s), re_syntax_options); + + if (!ret) + return NULL; + + /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */ + return (char *) gettext (__re_error_msgid + __re_error_msgid_idx[(int) ret]); +} + +#ifdef _LIBC +libc_freeres_fn (free_mem) +{ + __regfree (&re_comp_buf); +} +#endif + +#endif /* _REGEX_RE_COMP */ + +/* Internal entry point. + Compile the regular expression PATTERN, whose length is LENGTH. + SYNTAX indicate regular expression's syntax. */ + +static reg_errcode_t +re_compile_internal (regex_t *preg, const char * pattern, size_t length, + reg_syntax_t syntax) +{ + reg_errcode_t err = REG_NOERROR; + re_dfa_t *dfa; + re_string_t regexp; + + /* Initialize the pattern buffer. */ + preg->fastmap_accurate = 0; + preg->syntax = syntax; + preg->not_bol = preg->not_eol = 0; + preg->used = 0; + preg->re_nsub = 0; + preg->can_be_null = 0; + preg->regs_allocated = REGS_UNALLOCATED; + + /* Initialize the dfa. */ + dfa = (re_dfa_t *) preg->buffer; + if (BE (preg->allocated < sizeof (re_dfa_t), 0)) + { + /* If zero allocated, but buffer is non-null, try to realloc + enough space. This loses if buffer's address is bogus, but + that is the user's responsibility. If ->buffer is NULL this + is a simple allocation. */ + dfa = re_realloc (preg->buffer, re_dfa_t, 1); + if (dfa == NULL) + return REG_ESPACE; + preg->allocated = sizeof (re_dfa_t); + preg->buffer = (unsigned char *) dfa; + } + preg->used = sizeof (re_dfa_t); + + err = init_dfa (dfa, length); + if (BE (err != REG_NOERROR, 0)) + { + free_dfa_content (dfa); + preg->buffer = NULL; + preg->allocated = 0; + return err; + } +#ifdef DEBUG + /* Note: length+1 will not overflow since it is checked in init_dfa. */ + dfa->re_str = re_malloc (char, length + 1); + strncpy (dfa->re_str, pattern, length + 1); +#endif + + __libc_lock_init (dfa->lock); + + err = re_string_construct (®exp, pattern, length, preg->translate, + syntax & RE_ICASE, dfa); + if (BE (err != REG_NOERROR, 0)) + { + re_compile_internal_free_return: + free_workarea_compile (preg); + re_string_destruct (®exp); + free_dfa_content (dfa); + preg->buffer = NULL; + preg->allocated = 0; + return err; + } + + /* Parse the regular expression, and build a structure tree. */ + preg->re_nsub = 0; + dfa->str_tree = parse (®exp, preg, syntax, &err); + if (BE (dfa->str_tree == NULL, 0)) + goto re_compile_internal_free_return; + + /* Analyze the tree and create the nfa. */ + err = analyze (preg); + if (BE (err != REG_NOERROR, 0)) + goto re_compile_internal_free_return; + +#ifdef RE_ENABLE_I18N + /* If possible, do searching in single byte encoding to speed things up. */ + if (dfa->is_utf8 && !(syntax & RE_ICASE) && preg->translate == NULL) + optimize_utf8 (dfa); +#endif + + /* Then create the initial state of the dfa. */ + err = create_initial_state (dfa); + + /* Release work areas. */ + free_workarea_compile (preg); + re_string_destruct (®exp); + + if (BE (err != REG_NOERROR, 0)) + { + free_dfa_content (dfa); + preg->buffer = NULL; + preg->allocated = 0; + } + + return err; +} + +/* Initialize DFA. We use the length of the regular expression PAT_LEN + as the initial length of some arrays. */ + +static reg_errcode_t +init_dfa (re_dfa_t *dfa, size_t pat_len) +{ + __re_size_t table_size; +#ifdef RE_ENABLE_I18N + size_t max_i18n_object_size = MAX (sizeof (wchar_t), sizeof (wctype_t)); +#else + size_t max_i18n_object_size = 0; +#endif + size_t max_object_size = + MAX (sizeof (struct re_state_table_entry), + MAX (sizeof (re_token_t), + MAX (sizeof (re_node_set), + MAX (sizeof (regmatch_t), + max_i18n_object_size)))); + + memset (dfa, '\0', sizeof (re_dfa_t)); + + /* Force allocation of str_tree_storage the first time. */ + dfa->str_tree_storage_idx = BIN_TREE_STORAGE_SIZE; + + /* Avoid overflows. The extra "/ 2" is for the table_size doubling + calculation below, and for similar doubling calculations + elsewhere. And it's <= rather than <, because some of the + doubling calculations add 1 afterwards. */ + if (BE (SIZE_MAX / max_object_size / 2 <= pat_len, 0)) + return REG_ESPACE; + + dfa->nodes_alloc = pat_len + 1; + dfa->nodes = re_malloc (re_token_t, dfa->nodes_alloc); + + /* table_size = 2 ^ ceil(log pat_len) */ + for (table_size = 1; ; table_size <<= 1) + if (table_size > pat_len) + break; + + dfa->state_table = calloc (sizeof (struct re_state_table_entry), table_size); + dfa->state_hash_mask = table_size - 1; + + dfa->mb_cur_max = MB_CUR_MAX; +#ifdef _LIBC + if (dfa->mb_cur_max == 6 + && strcmp (_NL_CURRENT (LC_CTYPE, _NL_CTYPE_CODESET_NAME), "UTF-8") == 0) + dfa->is_utf8 = 1; + dfa->map_notascii = (_NL_CURRENT_WORD (LC_CTYPE, _NL_CTYPE_MAP_TO_NONASCII) + != 0); +#else + if (strcmp (locale_charset (), "UTF-8") == 0) + dfa->is_utf8 = 1; + + /* We check exhaustively in the loop below if this charset is a + superset of ASCII. */ + dfa->map_notascii = 0; +#endif + +#ifdef RE_ENABLE_I18N + if (dfa->mb_cur_max > 1) + { + if (dfa->is_utf8) + dfa->sb_char = (re_bitset_ptr_t) utf8_sb_map; + else + { + int i, j, ch; + + dfa->sb_char = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1); + if (BE (dfa->sb_char == NULL, 0)) + return REG_ESPACE; + + /* Set the bits corresponding to single byte chars. */ + for (i = 0, ch = 0; i < BITSET_WORDS; ++i) + for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch) + { + wint_t wch = __btowc (ch); + if (wch != WEOF) + dfa->sb_char[i] |= (bitset_word_t) 1 << j; +# ifndef _LIBC + if (isascii (ch) && wch != ch) + dfa->map_notascii = 1; +# endif + } + } + } +#endif + + if (BE (dfa->nodes == NULL || dfa->state_table == NULL, 0)) + return REG_ESPACE; + return REG_NOERROR; +} + +/* Initialize WORD_CHAR table, which indicate which character is + "word". In this case "word" means that it is the word construction + character used by some operators like "\<", "\>", etc. */ + +static void +internal_function +init_word_char (re_dfa_t *dfa) +{ + int i, j, ch; + dfa->word_ops_used = 1; + for (i = 0, ch = 0; i < BITSET_WORDS; ++i) + for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch) + if (isalnum (ch) || ch == '_') + dfa->word_char[i] |= (bitset_word_t) 1 << j; +} + +/* Free the work area which are only used while compiling. */ + +static void +free_workarea_compile (regex_t *preg) +{ + re_dfa_t *dfa = (re_dfa_t *) preg->buffer; + bin_tree_storage_t *storage, *next; + for (storage = dfa->str_tree_storage; storage; storage = next) + { + next = storage->next; + re_free (storage); + } + dfa->str_tree_storage = NULL; + dfa->str_tree_storage_idx = BIN_TREE_STORAGE_SIZE; + dfa->str_tree = NULL; + re_free (dfa->org_indices); + dfa->org_indices = NULL; +} + +/* Create initial states for all contexts. */ + +static reg_errcode_t +create_initial_state (re_dfa_t *dfa) +{ + Idx first, i; + reg_errcode_t err; + re_node_set init_nodes; + + /* Initial states have the epsilon closure of the node which is + the first node of the regular expression. */ + first = dfa->str_tree->first->node_idx; + dfa->init_node = first; + err = re_node_set_init_copy (&init_nodes, dfa->eclosures + first); + if (BE (err != REG_NOERROR, 0)) + return err; + + /* The back-references which are in initial states can epsilon transit, + since in this case all of the subexpressions can be null. + Then we add epsilon closures of the nodes which are the next nodes of + the back-references. */ + if (dfa->nbackref > 0) + for (i = 0; i < init_nodes.nelem; ++i) + { + Idx node_idx = init_nodes.elems[i]; + re_token_type_t type = dfa->nodes[node_idx].type; + + Idx clexp_idx; + if (type != OP_BACK_REF) + continue; + for (clexp_idx = 0; clexp_idx < init_nodes.nelem; ++clexp_idx) + { + re_token_t *clexp_node; + clexp_node = dfa->nodes + init_nodes.elems[clexp_idx]; + if (clexp_node->type == OP_CLOSE_SUBEXP + && clexp_node->opr.idx == dfa->nodes[node_idx].opr.idx) + break; + } + if (clexp_idx == init_nodes.nelem) + continue; + + if (type == OP_BACK_REF) + { + Idx dest_idx = dfa->edests[node_idx].elems[0]; + if (!re_node_set_contains (&init_nodes, dest_idx)) + { + re_node_set_merge (&init_nodes, dfa->eclosures + dest_idx); + i = 0; + } + } + } + + /* It must be the first time to invoke acquire_state. */ + dfa->init_state = re_acquire_state_context (&err, dfa, &init_nodes, 0); + /* We don't check ERR here, since the initial state must not be NULL. */ + if (BE (dfa->init_state == NULL, 0)) + return err; + if (dfa->init_state->has_constraint) + { + dfa->init_state_word = re_acquire_state_context (&err, dfa, &init_nodes, + CONTEXT_WORD); + dfa->init_state_nl = re_acquire_state_context (&err, dfa, &init_nodes, + CONTEXT_NEWLINE); + dfa->init_state_begbuf = re_acquire_state_context (&err, dfa, + &init_nodes, + CONTEXT_NEWLINE + | CONTEXT_BEGBUF); + if (BE (dfa->init_state_word == NULL || dfa->init_state_nl == NULL + || dfa->init_state_begbuf == NULL, 0)) + return err; + } + else + dfa->init_state_word = dfa->init_state_nl + = dfa->init_state_begbuf = dfa->init_state; + + re_node_set_free (&init_nodes); + return REG_NOERROR; +} + +#ifdef RE_ENABLE_I18N +/* If it is possible to do searching in single byte encoding instead of UTF-8 + to speed things up, set dfa->mb_cur_max to 1, clear is_utf8 and change + DFA nodes where needed. */ + +static void +optimize_utf8 (re_dfa_t *dfa) +{ + Idx node; + int i; + bool mb_chars = false; + bool has_period = false; + + for (node = 0; node < dfa->nodes_len; ++node) + switch (dfa->nodes[node].type) + { + case CHARACTER: + if (dfa->nodes[node].opr.c >= ASCII_CHARS) + mb_chars = true; + break; + case ANCHOR: + switch (dfa->nodes[node].opr.ctx_type) + { + case LINE_FIRST: + case LINE_LAST: + case BUF_FIRST: + case BUF_LAST: + break; + default: + /* Word anchors etc. cannot be handled. */ + return; + } + break; + case OP_PERIOD: + has_period = true; + break; + case OP_BACK_REF: + case OP_ALT: + case END_OF_RE: + case OP_DUP_ASTERISK: + case OP_OPEN_SUBEXP: + case OP_CLOSE_SUBEXP: + break; + case COMPLEX_BRACKET: + return; + case SIMPLE_BRACKET: + /* Just double check. */ + { + int rshift = (ASCII_CHARS % BITSET_WORD_BITS == 0 + ? 0 + : BITSET_WORD_BITS - ASCII_CHARS % BITSET_WORD_BITS); + for (i = ASCII_CHARS / BITSET_WORD_BITS; i < BITSET_WORDS; ++i) + { + if (dfa->nodes[node].opr.sbcset[i] >> rshift != 0) + return; + rshift = 0; + } + } + break; + default: + abort (); + } + + if (mb_chars || has_period) + for (node = 0; node < dfa->nodes_len; ++node) + { + if (dfa->nodes[node].type == CHARACTER + && dfa->nodes[node].opr.c >= ASCII_CHARS) + dfa->nodes[node].mb_partial = 0; + else if (dfa->nodes[node].type == OP_PERIOD) + dfa->nodes[node].type = OP_UTF8_PERIOD; + } + + /* The search can be in single byte locale. */ + dfa->mb_cur_max = 1; + dfa->is_utf8 = 0; + dfa->has_mb_node = dfa->nbackref > 0 || has_period; +} +#endif + +/* Analyze the structure tree, and calculate "first", "next", "edest", + "eclosure", and "inveclosure". */ + +static reg_errcode_t +analyze (regex_t *preg) +{ + re_dfa_t *dfa = (re_dfa_t *) preg->buffer; + reg_errcode_t ret; + + /* Allocate arrays. */ + dfa->nexts = re_malloc (Idx, dfa->nodes_alloc); + dfa->org_indices = re_malloc (Idx, dfa->nodes_alloc); + dfa->edests = re_malloc (re_node_set, dfa->nodes_alloc); + dfa->eclosures = re_malloc (re_node_set, dfa->nodes_alloc); + if (BE (dfa->nexts == NULL || dfa->org_indices == NULL || dfa->edests == NULL + || dfa->eclosures == NULL, 0)) + return REG_ESPACE; + + dfa->subexp_map = re_malloc (Idx, preg->re_nsub); + if (dfa->subexp_map != NULL) + { + Idx i; + for (i = 0; i < preg->re_nsub; i++) + dfa->subexp_map[i] = i; + preorder (dfa->str_tree, optimize_subexps, dfa); + for (i = 0; i < preg->re_nsub; i++) + if (dfa->subexp_map[i] != i) + break; + if (i == preg->re_nsub) + { + free (dfa->subexp_map); + dfa->subexp_map = NULL; + } + } + + ret = postorder (dfa->str_tree, lower_subexps, preg); + if (BE (ret != REG_NOERROR, 0)) + return ret; + ret = postorder (dfa->str_tree, calc_first, dfa); + if (BE (ret != REG_NOERROR, 0)) + return ret; + preorder (dfa->str_tree, calc_next, dfa); + ret = preorder (dfa->str_tree, link_nfa_nodes, dfa); + if (BE (ret != REG_NOERROR, 0)) + return ret; + ret = calc_eclosure (dfa); + if (BE (ret != REG_NOERROR, 0)) + return ret; + + /* We only need this during the prune_impossible_nodes pass in regexec.c; + skip it if p_i_n will not run, as calc_inveclosure can be quadratic. */ + if ((!preg->no_sub && preg->re_nsub > 0 && dfa->has_plural_match) + || dfa->nbackref) + { + dfa->inveclosures = re_malloc (re_node_set, dfa->nodes_len); + if (BE (dfa->inveclosures == NULL, 0)) + return REG_ESPACE; + ret = calc_inveclosure (dfa); + } + + return ret; +} + +/* Our parse trees are very unbalanced, so we cannot use a stack to + implement parse tree visits. Instead, we use parent pointers and + some hairy code in these two functions. */ +static reg_errcode_t +postorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)), + void *extra) +{ + bin_tree_t *node, *prev; + + for (node = root; ; ) + { + /* Descend down the tree, preferably to the left (or to the right + if that's the only child). */ + while (node->left || node->right) + if (node->left) + node = node->left; + else + node = node->right; + + do + { + reg_errcode_t err = fn (extra, node); + if (BE (err != REG_NOERROR, 0)) + return err; + if (node->parent == NULL) + return REG_NOERROR; + prev = node; + node = node->parent; + } + /* Go up while we have a node that is reached from the right. */ + while (node->right == prev || node->right == NULL); + node = node->right; + } +} + +static reg_errcode_t +preorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)), + void *extra) +{ + bin_tree_t *node; + + for (node = root; ; ) + { + reg_errcode_t err = fn (extra, node); + if (BE (err != REG_NOERROR, 0)) + return err; + + /* Go to the left node, or up and to the right. */ + if (node->left) + node = node->left; + else + { + bin_tree_t *prev = NULL; + while (node->right == prev || node->right == NULL) + { + prev = node; + node = node->parent; + if (!node) + return REG_NOERROR; + } + node = node->right; + } + } +} + +/* Optimization pass: if a SUBEXP is entirely contained, strip it and tell + re_search_internal to map the inner one's opr.idx to this one's. Adjust + backreferences as well. Requires a preorder visit. */ +static reg_errcode_t +optimize_subexps (void *extra, bin_tree_t *node) +{ + re_dfa_t *dfa = (re_dfa_t *) extra; + + if (node->token.type == OP_BACK_REF && dfa->subexp_map) + { + int idx = node->token.opr.idx; + node->token.opr.idx = dfa->subexp_map[idx]; + dfa->used_bkref_map |= 1 << node->token.opr.idx; + } + + else if (node->token.type == SUBEXP + && node->left && node->left->token.type == SUBEXP) + { + Idx other_idx = node->left->token.opr.idx; + + node->left = node->left->left; + if (node->left) + node->left->parent = node; + + dfa->subexp_map[other_idx] = dfa->subexp_map[node->token.opr.idx]; + if (other_idx < BITSET_WORD_BITS) + dfa->used_bkref_map &= ~((bitset_word_t) 1 << other_idx); + } + + return REG_NOERROR; +} + +/* Lowering pass: Turn each SUBEXP node into the appropriate concatenation + of OP_OPEN_SUBEXP, the body of the SUBEXP (if any) and OP_CLOSE_SUBEXP. */ +static reg_errcode_t +lower_subexps (void *extra, bin_tree_t *node) +{ + regex_t *preg = (regex_t *) extra; + reg_errcode_t err = REG_NOERROR; + + if (node->left && node->left->token.type == SUBEXP) + { + node->left = lower_subexp (&err, preg, node->left); + if (node->left) + node->left->parent = node; + } + if (node->right && node->right->token.type == SUBEXP) + { + node->right = lower_subexp (&err, preg, node->right); + if (node->right) + node->right->parent = node; + } + + return err; +} + +static bin_tree_t * +lower_subexp (reg_errcode_t *err, regex_t *preg, bin_tree_t *node) +{ + re_dfa_t *dfa = (re_dfa_t *) preg->buffer; + bin_tree_t *body = node->left; + bin_tree_t *op, *cls, *tree1, *tree; + + if (preg->no_sub + /* We do not optimize empty subexpressions, because otherwise we may + have bad CONCAT nodes with NULL children. This is obviously not + very common, so we do not lose much. An example that triggers + this case is the sed "script" /\(\)/x. */ + && node->left != NULL + && (node->token.opr.idx >= BITSET_WORD_BITS + || !(dfa->used_bkref_map + & ((bitset_word_t) 1 << node->token.opr.idx)))) + return node->left; + + /* Convert the SUBEXP node to the concatenation of an + OP_OPEN_SUBEXP, the contents, and an OP_CLOSE_SUBEXP. */ + op = create_tree (dfa, NULL, NULL, OP_OPEN_SUBEXP); + cls = create_tree (dfa, NULL, NULL, OP_CLOSE_SUBEXP); + tree1 = body ? create_tree (dfa, body, cls, CONCAT) : cls; + tree = create_tree (dfa, op, tree1, CONCAT); + if (BE (tree == NULL || tree1 == NULL || op == NULL || cls == NULL, 0)) + { + *err = REG_ESPACE; + return NULL; + } + + op->token.opr.idx = cls->token.opr.idx = node->token.opr.idx; + op->token.opt_subexp = cls->token.opt_subexp = node->token.opt_subexp; + return tree; +} + +/* Pass 1 in building the NFA: compute FIRST and create unlinked automaton + nodes. Requires a postorder visit. */ +static reg_errcode_t +calc_first (void *extra, bin_tree_t *node) +{ + re_dfa_t *dfa = (re_dfa_t *) extra; + if (node->token.type == CONCAT) + { + node->first = node->left->first; + node->node_idx = node->left->node_idx; + } + else + { + node->first = node; + node->node_idx = re_dfa_add_node (dfa, node->token); + if (BE (node->node_idx == REG_MISSING, 0)) + return REG_ESPACE; + } + return REG_NOERROR; +} + +/* Pass 2: compute NEXT on the tree. Preorder visit. */ +static reg_errcode_t +calc_next (void *extra, bin_tree_t *node) +{ + switch (node->token.type) + { + case OP_DUP_ASTERISK: + node->left->next = node; + break; + case CONCAT: + node->left->next = node->right->first; + node->right->next = node->next; + break; + default: + if (node->left) + node->left->next = node->next; + if (node->right) + node->right->next = node->next; + break; + } + return REG_NOERROR; +} + +/* Pass 3: link all DFA nodes to their NEXT node (any order will do). */ +static reg_errcode_t +link_nfa_nodes (void *extra, bin_tree_t *node) +{ + re_dfa_t *dfa = (re_dfa_t *) extra; + Idx idx = node->node_idx; + reg_errcode_t err = REG_NOERROR; + + switch (node->token.type) + { + case CONCAT: + break; + + case END_OF_RE: + assert (node->next == NULL); + break; + + case OP_DUP_ASTERISK: + case OP_ALT: + { + Idx left, right; + dfa->has_plural_match = 1; + if (node->left != NULL) + left = node->left->first->node_idx; + else + left = node->next->node_idx; + if (node->right != NULL) + right = node->right->first->node_idx; + else + right = node->next->node_idx; + assert (REG_VALID_INDEX (left)); + assert (REG_VALID_INDEX (right)); + err = re_node_set_init_2 (dfa->edests + idx, left, right); + } + break; + + case ANCHOR: + case OP_OPEN_SUBEXP: + case OP_CLOSE_SUBEXP: + err = re_node_set_init_1 (dfa->edests + idx, node->next->node_idx); + break; + + case OP_BACK_REF: + dfa->nexts[idx] = node->next->node_idx; + if (node->token.type == OP_BACK_REF) + re_node_set_init_1 (dfa->edests + idx, dfa->nexts[idx]); + break; + + default: + assert (!IS_EPSILON_NODE (node->token.type)); + dfa->nexts[idx] = node->next->node_idx; + break; + } + + return err; +} + +/* Duplicate the epsilon closure of the node ROOT_NODE. + Note that duplicated nodes have constraint INIT_CONSTRAINT in addition + to their own constraint. */ + +static reg_errcode_t +internal_function +duplicate_node_closure (re_dfa_t *dfa, Idx top_org_node, Idx top_clone_node, + Idx root_node, unsigned int init_constraint) +{ + Idx org_node, clone_node; + bool ok; + unsigned int constraint = init_constraint; + for (org_node = top_org_node, clone_node = top_clone_node;;) + { + Idx org_dest, clone_dest; + if (dfa->nodes[org_node].type == OP_BACK_REF) + { + /* If the back reference epsilon-transit, its destination must + also have the constraint. Then duplicate the epsilon closure + of the destination of the back reference, and store it in + edests of the back reference. */ + org_dest = dfa->nexts[org_node]; + re_node_set_empty (dfa->edests + clone_node); + clone_dest = duplicate_node (dfa, org_dest, constraint); + if (BE (clone_dest == REG_MISSING, 0)) + return REG_ESPACE; + dfa->nexts[clone_node] = dfa->nexts[org_node]; + ok = re_node_set_insert (dfa->edests + clone_node, clone_dest); + if (BE (! ok, 0)) + return REG_ESPACE; + } + else if (dfa->edests[org_node].nelem == 0) + { + /* In case of the node can't epsilon-transit, don't duplicate the + destination and store the original destination as the + destination of the node. */ + dfa->nexts[clone_node] = dfa->nexts[org_node]; + break; + } + else if (dfa->edests[org_node].nelem == 1) + { + /* In case of the node can epsilon-transit, and it has only one + destination. */ + org_dest = dfa->edests[org_node].elems[0]; + re_node_set_empty (dfa->edests + clone_node); + if (dfa->nodes[org_node].type == ANCHOR) + { + /* In case of the node has another constraint, append it. */ + if (org_node == root_node && clone_node != org_node) + { + /* ...but if the node is root_node itself, it means the + epsilon closure have a loop, then tie it to the + destination of the root_node. */ + ok = re_node_set_insert (dfa->edests + clone_node, org_dest); + if (BE (! ok, 0)) + return REG_ESPACE; + break; + } + constraint |= dfa->nodes[org_node].opr.ctx_type; + } + clone_dest = duplicate_node (dfa, org_dest, constraint); + if (BE (clone_dest == REG_MISSING, 0)) + return REG_ESPACE; + ok = re_node_set_insert (dfa->edests + clone_node, clone_dest); + if (BE (! ok, 0)) + return REG_ESPACE; + } + else /* dfa->edests[org_node].nelem == 2 */ + { + /* In case of the node can epsilon-transit, and it has two + destinations. In the bin_tree_t and DFA, that's '|' and '*'. */ + org_dest = dfa->edests[org_node].elems[0]; + re_node_set_empty (dfa->edests + clone_node); + /* Search for a duplicated node which satisfies the constraint. */ + clone_dest = search_duplicated_node (dfa, org_dest, constraint); + if (clone_dest == REG_MISSING) + { + /* There are no such a duplicated node, create a new one. */ + reg_errcode_t err; + clone_dest = duplicate_node (dfa, org_dest, constraint); + if (BE (clone_dest == REG_MISSING, 0)) + return REG_ESPACE; + ok = re_node_set_insert (dfa->edests + clone_node, clone_dest); + if (BE (! ok, 0)) + return REG_ESPACE; + err = duplicate_node_closure (dfa, org_dest, clone_dest, + root_node, constraint); + if (BE (err != REG_NOERROR, 0)) + return err; + } + else + { + /* There are a duplicated node which satisfy the constraint, + use it to avoid infinite loop. */ + ok = re_node_set_insert (dfa->edests + clone_node, clone_dest); + if (BE (! ok, 0)) + return REG_ESPACE; + } + + org_dest = dfa->edests[org_node].elems[1]; + clone_dest = duplicate_node (dfa, org_dest, constraint); + if (BE (clone_dest == REG_MISSING, 0)) + return REG_ESPACE; + ok = re_node_set_insert (dfa->edests + clone_node, clone_dest); + if (BE (! ok, 0)) + return REG_ESPACE; + } + org_node = org_dest; + clone_node = clone_dest; + } + return REG_NOERROR; +} + +/* Search for a node which is duplicated from the node ORG_NODE, and + satisfies the constraint CONSTRAINT. */ + +static Idx +search_duplicated_node (const re_dfa_t *dfa, Idx org_node, + unsigned int constraint) +{ + Idx idx; + for (idx = dfa->nodes_len - 1; dfa->nodes[idx].duplicated && idx > 0; --idx) + { + if (org_node == dfa->org_indices[idx] + && constraint == dfa->nodes[idx].constraint) + return idx; /* Found. */ + } + return REG_MISSING; /* Not found. */ +} + +/* Duplicate the node whose index is ORG_IDX and set the constraint CONSTRAINT. + Return the index of the new node, or REG_MISSING if insufficient storage is + available. */ + +static Idx +duplicate_node (re_dfa_t *dfa, Idx org_idx, unsigned int constraint) +{ + Idx dup_idx = re_dfa_add_node (dfa, dfa->nodes[org_idx]); + if (BE (dup_idx != REG_MISSING, 1)) + { + dfa->nodes[dup_idx].constraint = constraint; + if (dfa->nodes[org_idx].type == ANCHOR) + dfa->nodes[dup_idx].constraint |= dfa->nodes[org_idx].opr.ctx_type; + dfa->nodes[dup_idx].duplicated = 1; + + /* Store the index of the original node. */ + dfa->org_indices[dup_idx] = org_idx; + } + return dup_idx; +} + +static reg_errcode_t +calc_inveclosure (re_dfa_t *dfa) +{ + Idx src, idx; + bool ok; + for (idx = 0; idx < dfa->nodes_len; ++idx) + re_node_set_init_empty (dfa->inveclosures + idx); + + for (src = 0; src < dfa->nodes_len; ++src) + { + Idx *elems = dfa->eclosures[src].elems; + for (idx = 0; idx < dfa->eclosures[src].nelem; ++idx) + { + ok = re_node_set_insert_last (dfa->inveclosures + elems[idx], src); + if (BE (! ok, 0)) + return REG_ESPACE; + } + } + + return REG_NOERROR; +} + +/* Calculate "eclosure" for all the node in DFA. */ + +static reg_errcode_t +calc_eclosure (re_dfa_t *dfa) +{ + Idx node_idx; + bool incomplete; +#ifdef DEBUG + assert (dfa->nodes_len > 0); +#endif + incomplete = false; + /* For each nodes, calculate epsilon closure. */ + for (node_idx = 0; ; ++node_idx) + { + reg_errcode_t err; + re_node_set eclosure_elem; + if (node_idx == dfa->nodes_len) + { + if (!incomplete) + break; + incomplete = false; + node_idx = 0; + } + +#ifdef DEBUG + assert (dfa->eclosures[node_idx].nelem != REG_MISSING); +#endif + + /* If we have already calculated, skip it. */ + if (dfa->eclosures[node_idx].nelem != 0) + continue; + /* Calculate epsilon closure of `node_idx'. */ + err = calc_eclosure_iter (&eclosure_elem, dfa, node_idx, true); + if (BE (err != REG_NOERROR, 0)) + return err; + + if (dfa->eclosures[node_idx].nelem == 0) + { + incomplete = true; + re_node_set_free (&eclosure_elem); + } + } + return REG_NOERROR; +} + +/* Calculate epsilon closure of NODE. */ + +static reg_errcode_t +calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa, Idx node, bool root) +{ + reg_errcode_t err; + unsigned int constraint; + Idx i; + bool incomplete; + bool ok; + re_node_set eclosure; + incomplete = false; + err = re_node_set_alloc (&eclosure, dfa->edests[node].nelem + 1); + if (BE (err != REG_NOERROR, 0)) + return err; + + /* This indicates that we are calculating this node now. + We reference this value to avoid infinite loop. */ + dfa->eclosures[node].nelem = REG_MISSING; + + constraint = ((dfa->nodes[node].type == ANCHOR) + ? dfa->nodes[node].opr.ctx_type : 0); + /* If the current node has constraints, duplicate all nodes. + Since they must inherit the constraints. */ + if (constraint + && dfa->edests[node].nelem + && !dfa->nodes[dfa->edests[node].elems[0]].duplicated) + { + err = duplicate_node_closure (dfa, node, node, node, constraint); + if (BE (err != REG_NOERROR, 0)) + return err; + } + + /* Expand each epsilon destination nodes. */ + if (IS_EPSILON_NODE(dfa->nodes[node].type)) + for (i = 0; i < dfa->edests[node].nelem; ++i) + { + re_node_set eclosure_elem; + Idx edest = dfa->edests[node].elems[i]; + /* If calculating the epsilon closure of `edest' is in progress, + return intermediate result. */ + if (dfa->eclosures[edest].nelem == REG_MISSING) + { + incomplete = true; + continue; + } + /* If we haven't calculated the epsilon closure of `edest' yet, + calculate now. Otherwise use calculated epsilon closure. */ + if (dfa->eclosures[edest].nelem == 0) + { + err = calc_eclosure_iter (&eclosure_elem, dfa, edest, false); + if (BE (err != REG_NOERROR, 0)) + return err; + } + else + eclosure_elem = dfa->eclosures[edest]; + /* Merge the epsilon closure of `edest'. */ + re_node_set_merge (&eclosure, &eclosure_elem); + /* If the epsilon closure of `edest' is incomplete, + the epsilon closure of this node is also incomplete. */ + if (dfa->eclosures[edest].nelem == 0) + { + incomplete = true; + re_node_set_free (&eclosure_elem); + } + } + + /* Epsilon closures include itself. */ + ok = re_node_set_insert (&eclosure, node); + if (BE (! ok, 0)) + return REG_ESPACE; + if (incomplete && !root) + dfa->eclosures[node].nelem = 0; + else + dfa->eclosures[node] = eclosure; + *new_set = eclosure; + return REG_NOERROR; +} + +/* Functions for token which are used in the parser. */ + +/* Fetch a token from INPUT. + We must not use this function inside bracket expressions. */ + +static void +internal_function +fetch_token (re_token_t *result, re_string_t *input, reg_syntax_t syntax) +{ + re_string_skip_bytes (input, peek_token (result, input, syntax)); +} + +/* Peek a token from INPUT, and return the length of the token. + We must not use this function inside bracket expressions. */ + +static int +internal_function +peek_token (re_token_t *token, re_string_t *input, reg_syntax_t syntax) +{ + unsigned char c; + + if (re_string_eoi (input)) + { + token->type = END_OF_RE; + return 0; + } + + c = re_string_peek_byte (input, 0); + token->opr.c = c; + + token->word_char = 0; +#ifdef RE_ENABLE_I18N + token->mb_partial = 0; + if (input->mb_cur_max > 1 && + !re_string_first_byte (input, re_string_cur_idx (input))) + { + token->type = CHARACTER; + token->mb_partial = 1; + return 1; + } +#endif + if (c == '\\') + { + unsigned char c2; + if (re_string_cur_idx (input) + 1 >= re_string_length (input)) + { + token->type = BACK_SLASH; + return 1; + } + + c2 = re_string_peek_byte_case (input, 1); + token->opr.c = c2; + token->type = CHARACTER; +#ifdef RE_ENABLE_I18N + if (input->mb_cur_max > 1) + { + wint_t wc = re_string_wchar_at (input, + re_string_cur_idx (input) + 1); + token->word_char = IS_WIDE_WORD_CHAR (wc) != 0; + } + else +#endif + token->word_char = IS_WORD_CHAR (c2) != 0; + + switch (c2) + { + case '|': + if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_NO_BK_VBAR)) + token->type = OP_ALT; + break; + case '1': case '2': case '3': case '4': case '5': + case '6': case '7': case '8': case '9': + if (!(syntax & RE_NO_BK_REFS)) + { + token->type = OP_BACK_REF; + token->opr.idx = c2 - '1'; + } + break; + case '<': + if (!(syntax & RE_NO_GNU_OPS)) + { + token->type = ANCHOR; + token->opr.ctx_type = WORD_FIRST; + } + break; + case '>': + if (!(syntax & RE_NO_GNU_OPS)) + { + token->type = ANCHOR; + token->opr.ctx_type = WORD_LAST; + } + break; + case 'b': + if (!(syntax & RE_NO_GNU_OPS)) + { + token->type = ANCHOR; + token->opr.ctx_type = WORD_DELIM; + } + break; + case 'B': + if (!(syntax & RE_NO_GNU_OPS)) + { + token->type = ANCHOR; + token->opr.ctx_type = NOT_WORD_DELIM; + } + break; + case 'w': + if (!(syntax & RE_NO_GNU_OPS)) + token->type = OP_WORD; + break; + case 'W': + if (!(syntax & RE_NO_GNU_OPS)) + token->type = OP_NOTWORD; + break; + case 's': + if (!(syntax & RE_NO_GNU_OPS)) + token->type = OP_SPACE; + break; + case 'S': + if (!(syntax & RE_NO_GNU_OPS)) + token->type = OP_NOTSPACE; + break; + case '`': + if (!(syntax & RE_NO_GNU_OPS)) + { + token->type = ANCHOR; + token->opr.ctx_type = BUF_FIRST; + } + break; + case '\'': + if (!(syntax & RE_NO_GNU_OPS)) + { + token->type = ANCHOR; + token->opr.ctx_type = BUF_LAST; + } + break; + case '(': + if (!(syntax & RE_NO_BK_PARENS)) + token->type = OP_OPEN_SUBEXP; + break; + case ')': + if (!(syntax & RE_NO_BK_PARENS)) + token->type = OP_CLOSE_SUBEXP; + break; + case '+': + if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_BK_PLUS_QM)) + token->type = OP_DUP_PLUS; + break; + case '?': + if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_BK_PLUS_QM)) + token->type = OP_DUP_QUESTION; + break; + case '{': + if ((syntax & RE_INTERVALS) && (!(syntax & RE_NO_BK_BRACES))) + token->type = OP_OPEN_DUP_NUM; + break; + case '}': + if ((syntax & RE_INTERVALS) && (!(syntax & RE_NO_BK_BRACES))) + token->type = OP_CLOSE_DUP_NUM; + break; + default: + break; + } + return 2; + } + + token->type = CHARACTER; +#ifdef RE_ENABLE_I18N + if (input->mb_cur_max > 1) + { + wint_t wc = re_string_wchar_at (input, re_string_cur_idx (input)); + token->word_char = IS_WIDE_WORD_CHAR (wc) != 0; + } + else +#endif + token->word_char = IS_WORD_CHAR (token->opr.c); + + switch (c) + { + case '\n': + if (syntax & RE_NEWLINE_ALT) + token->type = OP_ALT; + break; + case '|': + if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_NO_BK_VBAR)) + token->type = OP_ALT; + break; + case '*': + token->type = OP_DUP_ASTERISK; + break; + case '+': + if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_BK_PLUS_QM)) + token->type = OP_DUP_PLUS; + break; + case '?': + if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_BK_PLUS_QM)) + token->type = OP_DUP_QUESTION; + break; + case '{': + if ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES)) + token->type = OP_OPEN_DUP_NUM; + break; + case '}': + if ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES)) + token->type = OP_CLOSE_DUP_NUM; + break; + case '(': + if (syntax & RE_NO_BK_PARENS) + token->type = OP_OPEN_SUBEXP; + break; + case ')': + if (syntax & RE_NO_BK_PARENS) + token->type = OP_CLOSE_SUBEXP; + break; + case '[': + token->type = OP_OPEN_BRACKET; + break; + case '.': + token->type = OP_PERIOD; + break; + case '^': + if (!(syntax & (RE_CONTEXT_INDEP_ANCHORS | RE_CARET_ANCHORS_HERE)) && + re_string_cur_idx (input) != 0) + { + char prev = re_string_peek_byte (input, -1); + if (!(syntax & RE_NEWLINE_ALT) || prev != '\n') + break; + } + token->type = ANCHOR; + token->opr.ctx_type = LINE_FIRST; + break; + case '$': + if (!(syntax & RE_CONTEXT_INDEP_ANCHORS) && + re_string_cur_idx (input) + 1 != re_string_length (input)) + { + re_token_t next; + re_string_skip_bytes (input, 1); + peek_token (&next, input, syntax); + re_string_skip_bytes (input, -1); + if (next.type != OP_ALT && next.type != OP_CLOSE_SUBEXP) + break; + } + token->type = ANCHOR; + token->opr.ctx_type = LINE_LAST; + break; + default: + break; + } + return 1; +} + +/* Peek a token from INPUT, and return the length of the token. + We must not use this function out of bracket expressions. */ + +static int +internal_function +peek_token_bracket (re_token_t *token, re_string_t *input, reg_syntax_t syntax) +{ + unsigned char c; + if (re_string_eoi (input)) + { + token->type = END_OF_RE; + return 0; + } + c = re_string_peek_byte (input, 0); + token->opr.c = c; + +#ifdef RE_ENABLE_I18N + if (input->mb_cur_max > 1 && + !re_string_first_byte (input, re_string_cur_idx (input))) + { + token->type = CHARACTER; + return 1; + } +#endif /* RE_ENABLE_I18N */ + + if (c == '\\' && (syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) + && re_string_cur_idx (input) + 1 < re_string_length (input)) + { + /* In this case, '\' escape a character. */ + unsigned char c2; + re_string_skip_bytes (input, 1); + c2 = re_string_peek_byte (input, 0); + token->opr.c = c2; + token->type = CHARACTER; + return 1; + } + if (c == '[') /* '[' is a special char in a bracket exps. */ + { + unsigned char c2; + int token_len; + if (re_string_cur_idx (input) + 1 < re_string_length (input)) + c2 = re_string_peek_byte (input, 1); + else + c2 = 0; + token->opr.c = c2; + token_len = 2; + switch (c2) + { + case '.': + token->type = OP_OPEN_COLL_ELEM; + break; + case '=': + token->type = OP_OPEN_EQUIV_CLASS; + break; + case ':': + if (syntax & RE_CHAR_CLASSES) + { + token->type = OP_OPEN_CHAR_CLASS; + break; + } + /* else fall through. */ + default: + token->type = CHARACTER; + token->opr.c = c; + token_len = 1; + break; + } + return token_len; + } + switch (c) + { + case '-': + token->type = OP_CHARSET_RANGE; + break; + case ']': + token->type = OP_CLOSE_BRACKET; + break; + case '^': + token->type = OP_NON_MATCH_LIST; + break; + default: + token->type = CHARACTER; + } + return 1; +} + +/* Functions for parser. */ + +/* Entry point of the parser. + Parse the regular expression REGEXP and return the structure tree. + If an error is occured, ERR is set by error code, and return NULL. + This function build the following tree, from regular expression : + CAT + / \ + / \ + EOR + + CAT means concatenation. + EOR means end of regular expression. */ + +static bin_tree_t * +parse (re_string_t *regexp, regex_t *preg, reg_syntax_t syntax, + reg_errcode_t *err) +{ + re_dfa_t *dfa = (re_dfa_t *) preg->buffer; + bin_tree_t *tree, *eor, *root; + re_token_t current_token; + dfa->syntax = syntax; + fetch_token (¤t_token, regexp, syntax | RE_CARET_ANCHORS_HERE); + tree = parse_reg_exp (regexp, preg, ¤t_token, syntax, 0, err); + if (BE (*err != REG_NOERROR && tree == NULL, 0)) + return NULL; + eor = create_tree (dfa, NULL, NULL, END_OF_RE); + if (tree != NULL) + root = create_tree (dfa, tree, eor, CONCAT); + else + root = eor; + if (BE (eor == NULL || root == NULL, 0)) + { + *err = REG_ESPACE; + return NULL; + } + return root; +} + +/* This function build the following tree, from regular expression + |: + ALT + / \ + / \ + + + ALT means alternative, which represents the operator `|'. */ + +static bin_tree_t * +parse_reg_exp (re_string_t *regexp, regex_t *preg, re_token_t *token, + reg_syntax_t syntax, Idx nest, reg_errcode_t *err) +{ + re_dfa_t *dfa = (re_dfa_t *) preg->buffer; + bin_tree_t *tree, *branch = NULL; + tree = parse_branch (regexp, preg, token, syntax, nest, err); + if (BE (*err != REG_NOERROR && tree == NULL, 0)) + return NULL; + + while (token->type == OP_ALT) + { + fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE); + if (token->type != OP_ALT && token->type != END_OF_RE + && (nest == 0 || token->type != OP_CLOSE_SUBEXP)) + { + branch = parse_branch (regexp, preg, token, syntax, nest, err); + if (BE (*err != REG_NOERROR && branch == NULL, 0)) + return NULL; + } + else + branch = NULL; + tree = create_tree (dfa, tree, branch, OP_ALT); + if (BE (tree == NULL, 0)) + { + *err = REG_ESPACE; + return NULL; + } + } + return tree; +} + +/* This function build the following tree, from regular expression + : + CAT + / \ + / \ + + + CAT means concatenation. */ + +static bin_tree_t * +parse_branch (re_string_t *regexp, regex_t *preg, re_token_t *token, + reg_syntax_t syntax, Idx nest, reg_errcode_t *err) +{ + bin_tree_t *tree, *expr; + re_dfa_t *dfa = (re_dfa_t *) preg->buffer; + tree = parse_expression (regexp, preg, token, syntax, nest, err); + if (BE (*err != REG_NOERROR && tree == NULL, 0)) + return NULL; + + while (token->type != OP_ALT && token->type != END_OF_RE + && (nest == 0 || token->type != OP_CLOSE_SUBEXP)) + { + expr = parse_expression (regexp, preg, token, syntax, nest, err); + if (BE (*err != REG_NOERROR && expr == NULL, 0)) + { + return NULL; + } + if (tree != NULL && expr != NULL) + { + tree = create_tree (dfa, tree, expr, CONCAT); + if (tree == NULL) + { + *err = REG_ESPACE; + return NULL; + } + } + else if (tree == NULL) + tree = expr; + /* Otherwise expr == NULL, we don't need to create new tree. */ + } + return tree; +} + +/* This function build the following tree, from regular expression a*: + * + | + a +*/ + +static bin_tree_t * +parse_expression (re_string_t *regexp, regex_t *preg, re_token_t *token, + reg_syntax_t syntax, Idx nest, reg_errcode_t *err) +{ + re_dfa_t *dfa = (re_dfa_t *) preg->buffer; + bin_tree_t *tree; + switch (token->type) + { + case CHARACTER: + tree = create_token_tree (dfa, NULL, NULL, token); + if (BE (tree == NULL, 0)) + { + *err = REG_ESPACE; + return NULL; + } +#ifdef RE_ENABLE_I18N + if (dfa->mb_cur_max > 1) + { + while (!re_string_eoi (regexp) + && !re_string_first_byte (regexp, re_string_cur_idx (regexp))) + { + bin_tree_t *mbc_remain; + fetch_token (token, regexp, syntax); + mbc_remain = create_token_tree (dfa, NULL, NULL, token); + tree = create_tree (dfa, tree, mbc_remain, CONCAT); + if (BE (mbc_remain == NULL || tree == NULL, 0)) + { + *err = REG_ESPACE; + return NULL; + } + } + } +#endif + break; + case OP_OPEN_SUBEXP: + tree = parse_sub_exp (regexp, preg, token, syntax, nest + 1, err); + if (BE (*err != REG_NOERROR && tree == NULL, 0)) + return NULL; + break; + case OP_OPEN_BRACKET: + tree = parse_bracket_exp (regexp, dfa, token, syntax, err); + if (BE (*err != REG_NOERROR && tree == NULL, 0)) + return NULL; + break; + case OP_BACK_REF: + if (!BE (dfa->completed_bkref_map & (1 << token->opr.idx), 1)) + { + *err = REG_ESUBREG; + return NULL; + } + dfa->used_bkref_map |= 1 << token->opr.idx; + tree = create_token_tree (dfa, NULL, NULL, token); + if (BE (tree == NULL, 0)) + { + *err = REG_ESPACE; + return NULL; + } + ++dfa->nbackref; + dfa->has_mb_node = 1; + break; + case OP_OPEN_DUP_NUM: + if (syntax & RE_CONTEXT_INVALID_DUP) + { + *err = REG_BADRPT; + return NULL; + } + /* FALLTHROUGH */ + case OP_DUP_ASTERISK: + case OP_DUP_PLUS: + case OP_DUP_QUESTION: + if (syntax & RE_CONTEXT_INVALID_OPS) + { + *err = REG_BADRPT; + return NULL; + } + else if (syntax & RE_CONTEXT_INDEP_OPS) + { + fetch_token (token, regexp, syntax); + return parse_expression (regexp, preg, token, syntax, nest, err); + } + /* else fall through */ + case OP_CLOSE_SUBEXP: + if ((token->type == OP_CLOSE_SUBEXP) && + !(syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)) + { + *err = REG_ERPAREN; + return NULL; + } + /* else fall through */ + case OP_CLOSE_DUP_NUM: + /* We treat it as a normal character. */ + + /* Then we can these characters as normal characters. */ + token->type = CHARACTER; + /* mb_partial and word_char bits should be initialized already + by peek_token. */ + tree = create_token_tree (dfa, NULL, NULL, token); + if (BE (tree == NULL, 0)) + { + *err = REG_ESPACE; + return NULL; + } + break; + case ANCHOR: + if ((token->opr.ctx_type + & (WORD_DELIM | NOT_WORD_DELIM | WORD_FIRST | WORD_LAST)) + && dfa->word_ops_used == 0) + init_word_char (dfa); + if (token->opr.ctx_type == WORD_DELIM + || token->opr.ctx_type == NOT_WORD_DELIM) + { + bin_tree_t *tree_first, *tree_last; + if (token->opr.ctx_type == WORD_DELIM) + { + token->opr.ctx_type = WORD_FIRST; + tree_first = create_token_tree (dfa, NULL, NULL, token); + token->opr.ctx_type = WORD_LAST; + } + else + { + token->opr.ctx_type = INSIDE_WORD; + tree_first = create_token_tree (dfa, NULL, NULL, token); + token->opr.ctx_type = INSIDE_NOTWORD; + } + tree_last = create_token_tree (dfa, NULL, NULL, token); + tree = create_tree (dfa, tree_first, tree_last, OP_ALT); + if (BE (tree_first == NULL || tree_last == NULL || tree == NULL, 0)) + { + *err = REG_ESPACE; + return NULL; + } + } + else + { + tree = create_token_tree (dfa, NULL, NULL, token); + if (BE (tree == NULL, 0)) + { + *err = REG_ESPACE; + return NULL; + } + } + /* We must return here, since ANCHORs can't be followed + by repetition operators. + eg. RE"^*" is invalid or "", + it must not be "". */ + fetch_token (token, regexp, syntax); + return tree; + case OP_PERIOD: + tree = create_token_tree (dfa, NULL, NULL, token); + if (BE (tree == NULL, 0)) + { + *err = REG_ESPACE; + return NULL; + } + if (dfa->mb_cur_max > 1) + dfa->has_mb_node = 1; + break; + case OP_WORD: + case OP_NOTWORD: + tree = build_charclass_op (dfa, regexp->trans, + (const unsigned char *) "alnum", + (const unsigned char *) "_", + token->type == OP_NOTWORD, err); + if (BE (*err != REG_NOERROR && tree == NULL, 0)) + return NULL; + break; + case OP_SPACE: + case OP_NOTSPACE: + tree = build_charclass_op (dfa, regexp->trans, + (const unsigned char *) "space", + (const unsigned char *) "", + token->type == OP_NOTSPACE, err); + if (BE (*err != REG_NOERROR && tree == NULL, 0)) + return NULL; + break; + case OP_ALT: + case END_OF_RE: + return NULL; + case BACK_SLASH: + *err = REG_EESCAPE; + return NULL; + default: + /* Must not happen? */ +#ifdef DEBUG + assert (0); +#endif + return NULL; + } + fetch_token (token, regexp, syntax); + + while (token->type == OP_DUP_ASTERISK || token->type == OP_DUP_PLUS + || token->type == OP_DUP_QUESTION || token->type == OP_OPEN_DUP_NUM) + { + tree = parse_dup_op (tree, regexp, dfa, token, syntax, err); + if (BE (*err != REG_NOERROR && tree == NULL, 0)) + return NULL; + /* In BRE consecutive duplications are not allowed. */ + if ((syntax & RE_CONTEXT_INVALID_DUP) + && (token->type == OP_DUP_ASTERISK + || token->type == OP_OPEN_DUP_NUM)) + { + *err = REG_BADRPT; + return NULL; + } + } + + return tree; +} + +/* This function build the following tree, from regular expression + (): + SUBEXP + | + +*/ + +static bin_tree_t * +parse_sub_exp (re_string_t *regexp, regex_t *preg, re_token_t *token, + reg_syntax_t syntax, Idx nest, reg_errcode_t *err) +{ + re_dfa_t *dfa = (re_dfa_t *) preg->buffer; + bin_tree_t *tree; + size_t cur_nsub; + cur_nsub = preg->re_nsub++; + + fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE); + + /* The subexpression may be a null string. */ + if (token->type == OP_CLOSE_SUBEXP) + tree = NULL; + else + { + tree = parse_reg_exp (regexp, preg, token, syntax, nest, err); + if (BE (*err == REG_NOERROR && token->type != OP_CLOSE_SUBEXP, 0)) + *err = REG_EPAREN; + if (BE (*err != REG_NOERROR, 0)) + return NULL; + } + + if (cur_nsub <= '9' - '1') + dfa->completed_bkref_map |= 1 << cur_nsub; + + tree = create_tree (dfa, tree, NULL, SUBEXP); + if (BE (tree == NULL, 0)) + { + *err = REG_ESPACE; + return NULL; + } + tree->token.opr.idx = cur_nsub; + return tree; +} + +/* This function parse repetition operators like "*", "+", "{1,3}" etc. */ + +static bin_tree_t * +parse_dup_op (bin_tree_t *elem, re_string_t *regexp, re_dfa_t *dfa, + re_token_t *token, reg_syntax_t syntax, reg_errcode_t *err) +{ + bin_tree_t *tree = NULL, *old_tree = NULL; + Idx i, start, end, start_idx = re_string_cur_idx (regexp); + re_token_t start_token = *token; + + if (token->type == OP_OPEN_DUP_NUM) + { + end = 0; + start = fetch_number (regexp, token, syntax); + if (start == REG_MISSING) + { + if (token->type == CHARACTER && token->opr.c == ',') + start = 0; /* We treat "{,m}" as "{0,m}". */ + else + { + *err = REG_BADBR; /* {} is invalid. */ + return NULL; + } + } + if (BE (start != REG_ERROR, 1)) + { + /* We treat "{n}" as "{n,n}". */ + end = ((token->type == OP_CLOSE_DUP_NUM) ? start + : ((token->type == CHARACTER && token->opr.c == ',') + ? fetch_number (regexp, token, syntax) : REG_ERROR)); + } + if (BE (start == REG_ERROR || end == REG_ERROR, 0)) + { + /* Invalid sequence. */ + if (BE (!(syntax & RE_INVALID_INTERVAL_ORD), 0)) + { + if (token->type == END_OF_RE) + *err = REG_EBRACE; + else + *err = REG_BADBR; + + return NULL; + } + + /* If the syntax bit is set, rollback. */ + re_string_set_index (regexp, start_idx); + *token = start_token; + token->type = CHARACTER; + /* mb_partial and word_char bits should be already initialized by + peek_token. */ + return elem; + } + + if (BE (end != REG_MISSING && start > end, 0)) + { + /* First number greater than second. */ + *err = REG_BADBR; + return NULL; + } + } + else + { + start = (token->type == OP_DUP_PLUS) ? 1 : 0; + end = (token->type == OP_DUP_QUESTION) ? 1 : REG_MISSING; + } + + fetch_token (token, regexp, syntax); + + if (BE (elem == NULL, 0)) + return NULL; + if (BE (start == 0 && end == 0, 0)) + { + postorder (elem, free_tree, NULL); + return NULL; + } + + /* Extract "{n,m}" to "...{0,}". */ + if (BE (start > 0, 0)) + { + tree = elem; + for (i = 2; i <= start; ++i) + { + elem = duplicate_tree (elem, dfa); + tree = create_tree (dfa, tree, elem, CONCAT); + if (BE (elem == NULL || tree == NULL, 0)) + goto parse_dup_op_espace; + } + + if (start == end) + return tree; + + /* Duplicate ELEM before it is marked optional. */ + elem = duplicate_tree (elem, dfa); + old_tree = tree; + } + else + old_tree = NULL; + + if (elem->token.type == SUBEXP) + postorder (elem, mark_opt_subexp, (void *) (long) elem->token.opr.idx); + + tree = create_tree (dfa, elem, NULL, + (end == REG_MISSING ? OP_DUP_ASTERISK : OP_ALT)); + if (BE (tree == NULL, 0)) + goto parse_dup_op_espace; + + /* This loop is actually executed only when end != REG_MISSING, + to rewrite {0,n} as ((...?)?)?... We have + already created the start+1-th copy. */ + if ((Idx) -1 < 0 || end != REG_MISSING) + for (i = start + 2; i <= end; ++i) + { + elem = duplicate_tree (elem, dfa); + tree = create_tree (dfa, tree, elem, CONCAT); + if (BE (elem == NULL || tree == NULL, 0)) + goto parse_dup_op_espace; + + tree = create_tree (dfa, tree, NULL, OP_ALT); + if (BE (tree == NULL, 0)) + goto parse_dup_op_espace; + } + + if (old_tree) + tree = create_tree (dfa, old_tree, tree, CONCAT); + + return tree; + + parse_dup_op_espace: + *err = REG_ESPACE; + return NULL; +} + +/* Size of the names for collating symbol/equivalence_class/character_class. + I'm not sure, but maybe enough. */ +#define BRACKET_NAME_BUF_SIZE 32 + +#ifndef _LIBC + /* Local function for parse_bracket_exp only used in case of NOT _LIBC. + Build the range expression which starts from START_ELEM, and ends + at END_ELEM. The result are written to MBCSET and SBCSET. + RANGE_ALLOC is the allocated size of mbcset->range_starts, and + mbcset->range_ends, is a pointer argument sinse we may + update it. */ + +static reg_errcode_t +internal_function +# ifdef RE_ENABLE_I18N +build_range_exp (bitset_t sbcset, re_charset_t *mbcset, Idx *range_alloc, + bracket_elem_t *start_elem, bracket_elem_t *end_elem) +# else /* not RE_ENABLE_I18N */ +build_range_exp (bitset_t sbcset, bracket_elem_t *start_elem, + bracket_elem_t *end_elem) +# endif /* not RE_ENABLE_I18N */ +{ + unsigned int start_ch, end_ch; + /* Equivalence Classes and Character Classes can't be a range start/end. */ + if (BE (start_elem->type == EQUIV_CLASS || start_elem->type == CHAR_CLASS + || end_elem->type == EQUIV_CLASS || end_elem->type == CHAR_CLASS, + 0)) + return REG_ERANGE; + + /* We can handle no multi character collating elements without libc + support. */ + if (BE ((start_elem->type == COLL_SYM + && strlen ((char *) start_elem->opr.name) > 1) + || (end_elem->type == COLL_SYM + && strlen ((char *) end_elem->opr.name) > 1), 0)) + return REG_ECOLLATE; + +# ifdef RE_ENABLE_I18N + { + wchar_t wc; + wint_t start_wc; + wint_t end_wc; + wchar_t cmp_buf[6] = {L'\0', L'\0', L'\0', L'\0', L'\0', L'\0'}; + + start_ch = ((start_elem->type == SB_CHAR) ? start_elem->opr.ch + : ((start_elem->type == COLL_SYM) ? start_elem->opr.name[0] + : 0)); + end_ch = ((end_elem->type == SB_CHAR) ? end_elem->opr.ch + : ((end_elem->type == COLL_SYM) ? end_elem->opr.name[0] + : 0)); + start_wc = ((start_elem->type == SB_CHAR || start_elem->type == COLL_SYM) + ? __btowc (start_ch) : start_elem->opr.wch); + end_wc = ((end_elem->type == SB_CHAR || end_elem->type == COLL_SYM) + ? __btowc (end_ch) : end_elem->opr.wch); + if (start_wc == WEOF || end_wc == WEOF) + return REG_ECOLLATE; + cmp_buf[0] = start_wc; + cmp_buf[4] = end_wc; + if (wcscoll (cmp_buf, cmp_buf + 4) > 0) + return REG_ERANGE; + + /* Got valid collation sequence values, add them as a new entry. + However, for !_LIBC we have no collation elements: if the + character set is single byte, the single byte character set + that we build below suffices. parse_bracket_exp passes + no MBCSET if dfa->mb_cur_max == 1. */ + if (mbcset) + { + /* Check the space of the arrays. */ + if (BE (*range_alloc == mbcset->nranges, 0)) + { + /* There is not enough space, need realloc. */ + wchar_t *new_array_start, *new_array_end; + Idx new_nranges; + + /* +1 in case of mbcset->nranges is 0. */ + new_nranges = 2 * mbcset->nranges + 1; + /* Use realloc since mbcset->range_starts and mbcset->range_ends + are NULL if *range_alloc == 0. */ + new_array_start = re_realloc (mbcset->range_starts, wchar_t, + new_nranges); + new_array_end = re_realloc (mbcset->range_ends, wchar_t, + new_nranges); + + if (BE (new_array_start == NULL || new_array_end == NULL, 0)) + return REG_ESPACE; + + mbcset->range_starts = new_array_start; + mbcset->range_ends = new_array_end; + *range_alloc = new_nranges; + } + + mbcset->range_starts[mbcset->nranges] = start_wc; + mbcset->range_ends[mbcset->nranges++] = end_wc; + } + + /* Build the table for single byte characters. */ + for (wc = 0; wc < SBC_MAX; ++wc) + { + cmp_buf[2] = wc; + if (wcscoll (cmp_buf, cmp_buf + 2) <= 0 + && wcscoll (cmp_buf + 2, cmp_buf + 4) <= 0) + bitset_set (sbcset, wc); + } + } +# else /* not RE_ENABLE_I18N */ + { + unsigned int ch; + start_ch = ((start_elem->type == SB_CHAR ) ? start_elem->opr.ch + : ((start_elem->type == COLL_SYM) ? start_elem->opr.name[0] + : 0)); + end_ch = ((end_elem->type == SB_CHAR ) ? end_elem->opr.ch + : ((end_elem->type == COLL_SYM) ? end_elem->opr.name[0] + : 0)); + if (start_ch > end_ch) + return REG_ERANGE; + /* Build the table for single byte characters. */ + for (ch = 0; ch < SBC_MAX; ++ch) + if (start_ch <= ch && ch <= end_ch) + bitset_set (sbcset, ch); + } +# endif /* not RE_ENABLE_I18N */ + return REG_NOERROR; +} +#endif /* not _LIBC */ + +#ifndef _LIBC +/* Helper function for parse_bracket_exp only used in case of NOT _LIBC.. + Build the collating element which is represented by NAME. + The result are written to MBCSET and SBCSET. + COLL_SYM_ALLOC is the allocated size of mbcset->coll_sym, is a + pointer argument since we may update it. */ + +static reg_errcode_t +internal_function +build_collating_symbol (bitset_t sbcset, +# ifdef RE_ENABLE_I18N + re_charset_t *mbcset, Idx *coll_sym_alloc, +# endif + const unsigned char *name) +{ + size_t name_len = strlen ((const char *) name); + if (BE (name_len != 1, 0)) + return REG_ECOLLATE; + else + { + bitset_set (sbcset, name[0]); + return REG_NOERROR; + } +} +#endif /* not _LIBC */ + +/* This function parse bracket expression like "[abc]", "[a-c]", + "[[.a-a.]]" etc. */ + +static bin_tree_t * +parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token, + reg_syntax_t syntax, reg_errcode_t *err) +{ +#ifdef _LIBC + const unsigned char *collseqmb; + const char *collseqwc; + uint32_t nrules; + int32_t table_size; + const int32_t *symb_table; + const unsigned char *extra; + + /* Local function for parse_bracket_exp used in _LIBC environement. + Seek the collating symbol entry correspondings to NAME. + Return the index of the symbol in the SYMB_TABLE. */ + + auto inline int32_t + __attribute ((always_inline)) + seek_collating_symbol_entry (name, name_len) + const unsigned char *name; + size_t name_len; + { + int32_t hash = elem_hash ((const char *) name, name_len); + int32_t elem = hash % table_size; + if (symb_table[2 * elem] != 0) + { + int32_t second = hash % (table_size - 2) + 1; + + do + { + /* First compare the hashing value. */ + if (symb_table[2 * elem] == hash + /* Compare the length of the name. */ + && name_len == extra[symb_table[2 * elem + 1]] + /* Compare the name. */ + && memcmp (name, &extra[symb_table[2 * elem + 1] + 1], + name_len) == 0) + { + /* Yep, this is the entry. */ + break; + } + + /* Next entry. */ + elem += second; + } + while (symb_table[2 * elem] != 0); + } + return elem; + } + + /* Local function for parse_bracket_exp used in _LIBC environement. + Look up the collation sequence value of BR_ELEM. + Return the value if succeeded, UINT_MAX otherwise. */ + + auto inline unsigned int + __attribute ((always_inline)) + lookup_collation_sequence_value (br_elem) + bracket_elem_t *br_elem; + { + if (br_elem->type == SB_CHAR) + { + /* + if (MB_CUR_MAX == 1) + */ + if (nrules == 0) + return collseqmb[br_elem->opr.ch]; + else + { + wint_t wc = __btowc (br_elem->opr.ch); + return __collseq_table_lookup (collseqwc, wc); + } + } + else if (br_elem->type == MB_CHAR) + { + return __collseq_table_lookup (collseqwc, br_elem->opr.wch); + } + else if (br_elem->type == COLL_SYM) + { + size_t sym_name_len = strlen ((char *) br_elem->opr.name); + if (nrules != 0) + { + int32_t elem, idx; + elem = seek_collating_symbol_entry (br_elem->opr.name, + sym_name_len); + if (symb_table[2 * elem] != 0) + { + /* We found the entry. */ + idx = symb_table[2 * elem + 1]; + /* Skip the name of collating element name. */ + idx += 1 + extra[idx]; + /* Skip the byte sequence of the collating element. */ + idx += 1 + extra[idx]; + /* Adjust for the alignment. */ + idx = (idx + 3) & ~3; + /* Skip the multibyte collation sequence value. */ + idx += sizeof (unsigned int); + /* Skip the wide char sequence of the collating element. */ + idx += sizeof (unsigned int) * + (1 + *(unsigned int *) (extra + idx)); + /* Return the collation sequence value. */ + return *(unsigned int *) (extra + idx); + } + else if (symb_table[2 * elem] == 0 && sym_name_len == 1) + { + /* No valid character. Match it as a single byte + character. */ + return collseqmb[br_elem->opr.name[0]]; + } + } + else if (sym_name_len == 1) + return collseqmb[br_elem->opr.name[0]]; + } + return UINT_MAX; + } + + /* Local function for parse_bracket_exp used in _LIBC environement. + Build the range expression which starts from START_ELEM, and ends + at END_ELEM. The result are written to MBCSET and SBCSET. + RANGE_ALLOC is the allocated size of mbcset->range_starts, and + mbcset->range_ends, is a pointer argument sinse we may + update it. */ + + auto inline reg_errcode_t + __attribute ((always_inline)) + build_range_exp (sbcset, mbcset, range_alloc, start_elem, end_elem) + re_charset_t *mbcset; + Idx *range_alloc; + bitset_t sbcset; + bracket_elem_t *start_elem, *end_elem; + { + unsigned int ch; + uint32_t start_collseq; + uint32_t end_collseq; + + /* Equivalence Classes and Character Classes can't be a range + start/end. */ + if (BE (start_elem->type == EQUIV_CLASS || start_elem->type == CHAR_CLASS + || end_elem->type == EQUIV_CLASS || end_elem->type == CHAR_CLASS, + 0)) + return REG_ERANGE; + + start_collseq = lookup_collation_sequence_value (start_elem); + end_collseq = lookup_collation_sequence_value (end_elem); + /* Check start/end collation sequence values. */ + if (BE (start_collseq == UINT_MAX || end_collseq == UINT_MAX, 0)) + return REG_ECOLLATE; + if (BE ((syntax & RE_NO_EMPTY_RANGES) && start_collseq > end_collseq, 0)) + return REG_ERANGE; + + /* Got valid collation sequence values, add them as a new entry. + However, if we have no collation elements, and the character set + is single byte, the single byte character set that we + build below suffices. */ + if (nrules > 0 || dfa->mb_cur_max > 1) + { + /* Check the space of the arrays. */ + if (BE (*range_alloc == mbcset->nranges, 0)) + { + /* There is not enough space, need realloc. */ + uint32_t *new_array_start; + uint32_t *new_array_end; + Idx new_nranges; + + /* +1 in case of mbcset->nranges is 0. */ + new_nranges = 2 * mbcset->nranges + 1; + new_array_start = re_realloc (mbcset->range_starts, uint32_t, + new_nranges); + new_array_end = re_realloc (mbcset->range_ends, uint32_t, + new_nranges); + + if (BE (new_array_start == NULL || new_array_end == NULL, 0)) + return REG_ESPACE; + + mbcset->range_starts = new_array_start; + mbcset->range_ends = new_array_end; + *range_alloc = new_nranges; + } + + mbcset->range_starts[mbcset->nranges] = start_collseq; + mbcset->range_ends[mbcset->nranges++] = end_collseq; + } + + /* Build the table for single byte characters. */ + for (ch = 0; ch < SBC_MAX; ch++) + { + uint32_t ch_collseq; + /* + if (MB_CUR_MAX == 1) + */ + if (nrules == 0) + ch_collseq = collseqmb[ch]; + else + ch_collseq = __collseq_table_lookup (collseqwc, __btowc (ch)); + if (start_collseq <= ch_collseq && ch_collseq <= end_collseq) + bitset_set (sbcset, ch); + } + return REG_NOERROR; + } + + /* Local function for parse_bracket_exp used in _LIBC environement. + Build the collating element which is represented by NAME. + The result are written to MBCSET and SBCSET. + COLL_SYM_ALLOC is the allocated size of mbcset->coll_sym, is a + pointer argument sinse we may update it. */ + + auto inline reg_errcode_t + __attribute ((always_inline)) + build_collating_symbol (sbcset, mbcset, coll_sym_alloc, name) + re_charset_t *mbcset; + Idx *coll_sym_alloc; + bitset_t sbcset; + const unsigned char *name; + { + int32_t elem, idx; + size_t name_len = strlen ((const char *) name); + if (nrules != 0) + { + elem = seek_collating_symbol_entry (name, name_len); + if (symb_table[2 * elem] != 0) + { + /* We found the entry. */ + idx = symb_table[2 * elem + 1]; + /* Skip the name of collating element name. */ + idx += 1 + extra[idx]; + } + else if (symb_table[2 * elem] == 0 && name_len == 1) + { + /* No valid character, treat it as a normal + character. */ + bitset_set (sbcset, name[0]); + return REG_NOERROR; + } + else + return REG_ECOLLATE; + + /* Got valid collation sequence, add it as a new entry. */ + /* Check the space of the arrays. */ + if (BE (*coll_sym_alloc == mbcset->ncoll_syms, 0)) + { + /* Not enough, realloc it. */ + /* +1 in case of mbcset->ncoll_syms is 0. */ + Idx new_coll_sym_alloc = 2 * mbcset->ncoll_syms + 1; + /* Use realloc since mbcset->coll_syms is NULL + if *alloc == 0. */ + int32_t *new_coll_syms = re_realloc (mbcset->coll_syms, int32_t, + new_coll_sym_alloc); + if (BE (new_coll_syms == NULL, 0)) + return REG_ESPACE; + mbcset->coll_syms = new_coll_syms; + *coll_sym_alloc = new_coll_sym_alloc; + } + mbcset->coll_syms[mbcset->ncoll_syms++] = idx; + return REG_NOERROR; + } + else + { + if (BE (name_len != 1, 0)) + return REG_ECOLLATE; + else + { + bitset_set (sbcset, name[0]); + return REG_NOERROR; + } + } + } +#endif + + re_token_t br_token; + re_bitset_ptr_t sbcset; +#ifdef RE_ENABLE_I18N + re_charset_t *mbcset; + Idx coll_sym_alloc = 0, range_alloc = 0, mbchar_alloc = 0; + Idx equiv_class_alloc = 0, char_class_alloc = 0; +#endif /* not RE_ENABLE_I18N */ + bool non_match = false; + bin_tree_t *work_tree; + int token_len; + bool first_round = true; +#ifdef _LIBC + collseqmb = (const unsigned char *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQMB); + nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES); + if (nrules) + { + /* + if (MB_CUR_MAX > 1) + */ + collseqwc = _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQWC); + table_size = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_SYMB_HASH_SIZEMB); + symb_table = (const int32_t *) _NL_CURRENT (LC_COLLATE, + _NL_COLLATE_SYMB_TABLEMB); + extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE, + _NL_COLLATE_SYMB_EXTRAMB); + } +#endif + sbcset = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1); +#ifdef RE_ENABLE_I18N + mbcset = (re_charset_t *) calloc (sizeof (re_charset_t), 1); +#endif /* RE_ENABLE_I18N */ +#ifdef RE_ENABLE_I18N + if (BE (sbcset == NULL || mbcset == NULL, 0)) +#else + if (BE (sbcset == NULL, 0)) +#endif /* RE_ENABLE_I18N */ + { + *err = REG_ESPACE; + return NULL; + } + + token_len = peek_token_bracket (token, regexp, syntax); + if (BE (token->type == END_OF_RE, 0)) + { + *err = REG_BADPAT; + goto parse_bracket_exp_free_return; + } + if (token->type == OP_NON_MATCH_LIST) + { +#ifdef RE_ENABLE_I18N + mbcset->non_match = 1; +#endif /* not RE_ENABLE_I18N */ + non_match = true; + if (syntax & RE_HAT_LISTS_NOT_NEWLINE) + bitset_set (sbcset, '\n'); + re_string_skip_bytes (regexp, token_len); /* Skip a token. */ + token_len = peek_token_bracket (token, regexp, syntax); + if (BE (token->type == END_OF_RE, 0)) + { + *err = REG_BADPAT; + goto parse_bracket_exp_free_return; + } + } + + /* We treat the first ']' as a normal character. */ + if (token->type == OP_CLOSE_BRACKET) + token->type = CHARACTER; + + while (1) + { + bracket_elem_t start_elem, end_elem; + unsigned char start_name_buf[BRACKET_NAME_BUF_SIZE]; + unsigned char end_name_buf[BRACKET_NAME_BUF_SIZE]; + reg_errcode_t ret; + int token_len2 = 0; + bool is_range_exp = false; + re_token_t token2; + + start_elem.opr.name = start_name_buf; + ret = parse_bracket_element (&start_elem, regexp, token, token_len, dfa, + syntax, first_round); + if (BE (ret != REG_NOERROR, 0)) + { + *err = ret; + goto parse_bracket_exp_free_return; + } + first_round = false; + + /* Get information about the next token. We need it in any case. */ + token_len = peek_token_bracket (token, regexp, syntax); + + /* Do not check for ranges if we know they are not allowed. */ + if (start_elem.type != CHAR_CLASS && start_elem.type != EQUIV_CLASS) + { + if (BE (token->type == END_OF_RE, 0)) + { + *err = REG_EBRACK; + goto parse_bracket_exp_free_return; + } + if (token->type == OP_CHARSET_RANGE) + { + re_string_skip_bytes (regexp, token_len); /* Skip '-'. */ + token_len2 = peek_token_bracket (&token2, regexp, syntax); + if (BE (token2.type == END_OF_RE, 0)) + { + *err = REG_EBRACK; + goto parse_bracket_exp_free_return; + } + if (token2.type == OP_CLOSE_BRACKET) + { + /* We treat the last '-' as a normal character. */ + re_string_skip_bytes (regexp, -token_len); + token->type = CHARACTER; + } + else + is_range_exp = true; + } + } + + if (is_range_exp == true) + { + end_elem.opr.name = end_name_buf; + ret = parse_bracket_element (&end_elem, regexp, &token2, token_len2, + dfa, syntax, true); + if (BE (ret != REG_NOERROR, 0)) + { + *err = ret; + goto parse_bracket_exp_free_return; + } + + token_len = peek_token_bracket (token, regexp, syntax); + +#ifdef _LIBC + *err = build_range_exp (sbcset, mbcset, &range_alloc, + &start_elem, &end_elem); +#else +# ifdef RE_ENABLE_I18N + *err = build_range_exp (sbcset, + dfa->mb_cur_max > 1 ? mbcset : NULL, + &range_alloc, &start_elem, &end_elem); +# else + *err = build_range_exp (sbcset, &start_elem, &end_elem); +# endif +#endif /* RE_ENABLE_I18N */ + if (BE (*err != REG_NOERROR, 0)) + goto parse_bracket_exp_free_return; + } + else + { + switch (start_elem.type) + { + case SB_CHAR: + bitset_set (sbcset, start_elem.opr.ch); + break; +#ifdef RE_ENABLE_I18N + case MB_CHAR: + /* Check whether the array has enough space. */ + if (BE (mbchar_alloc == mbcset->nmbchars, 0)) + { + wchar_t *new_mbchars; + /* Not enough, realloc it. */ + /* +1 in case of mbcset->nmbchars is 0. */ + mbchar_alloc = 2 * mbcset->nmbchars + 1; + /* Use realloc since array is NULL if *alloc == 0. */ + new_mbchars = re_realloc (mbcset->mbchars, wchar_t, + mbchar_alloc); + if (BE (new_mbchars == NULL, 0)) + goto parse_bracket_exp_espace; + mbcset->mbchars = new_mbchars; + } + mbcset->mbchars[mbcset->nmbchars++] = start_elem.opr.wch; + break; +#endif /* RE_ENABLE_I18N */ + case EQUIV_CLASS: + *err = build_equiv_class (sbcset, +#ifdef RE_ENABLE_I18N + mbcset, &equiv_class_alloc, +#endif /* RE_ENABLE_I18N */ + start_elem.opr.name); + if (BE (*err != REG_NOERROR, 0)) + goto parse_bracket_exp_free_return; + break; + case COLL_SYM: + *err = build_collating_symbol (sbcset, +#ifdef RE_ENABLE_I18N + mbcset, &coll_sym_alloc, +#endif /* RE_ENABLE_I18N */ + start_elem.opr.name); + if (BE (*err != REG_NOERROR, 0)) + goto parse_bracket_exp_free_return; + break; + case CHAR_CLASS: + *err = build_charclass (regexp->trans, sbcset, +#ifdef RE_ENABLE_I18N + mbcset, &char_class_alloc, +#endif /* RE_ENABLE_I18N */ + start_elem.opr.name, syntax); + if (BE (*err != REG_NOERROR, 0)) + goto parse_bracket_exp_free_return; + break; + default: + assert (0); + break; + } + } + if (BE (token->type == END_OF_RE, 0)) + { + *err = REG_EBRACK; + goto parse_bracket_exp_free_return; + } + if (token->type == OP_CLOSE_BRACKET) + break; + } + + re_string_skip_bytes (regexp, token_len); /* Skip a token. */ + + /* If it is non-matching list. */ + if (non_match) + bitset_not (sbcset); + +#ifdef RE_ENABLE_I18N + /* Ensure only single byte characters are set. */ + if (dfa->mb_cur_max > 1) + bitset_mask (sbcset, dfa->sb_char); + + if (mbcset->nmbchars || mbcset->ncoll_syms || mbcset->nequiv_classes + || mbcset->nranges || (dfa->mb_cur_max > 1 && (mbcset->nchar_classes + || mbcset->non_match))) + { + bin_tree_t *mbc_tree; + int sbc_idx; + /* Build a tree for complex bracket. */ + dfa->has_mb_node = 1; + br_token.type = COMPLEX_BRACKET; + br_token.opr.mbcset = mbcset; + mbc_tree = create_token_tree (dfa, NULL, NULL, &br_token); + if (BE (mbc_tree == NULL, 0)) + goto parse_bracket_exp_espace; + for (sbc_idx = 0; sbc_idx < BITSET_WORDS; ++sbc_idx) + if (sbcset[sbc_idx]) + break; + /* If there are no bits set in sbcset, there is no point + of having both SIMPLE_BRACKET and COMPLEX_BRACKET. */ + if (sbc_idx < BITSET_WORDS) + { + /* Build a tree for simple bracket. */ + br_token.type = SIMPLE_BRACKET; + br_token.opr.sbcset = sbcset; + work_tree = create_token_tree (dfa, NULL, NULL, &br_token); + if (BE (work_tree == NULL, 0)) + goto parse_bracket_exp_espace; + + /* Then join them by ALT node. */ + work_tree = create_tree (dfa, work_tree, mbc_tree, OP_ALT); + if (BE (work_tree == NULL, 0)) + goto parse_bracket_exp_espace; + } + else + { + re_free (sbcset); + work_tree = mbc_tree; + } + } + else +#endif /* not RE_ENABLE_I18N */ + { +#ifdef RE_ENABLE_I18N + free_charset (mbcset); +#endif + /* Build a tree for simple bracket. */ + br_token.type = SIMPLE_BRACKET; + br_token.opr.sbcset = sbcset; + work_tree = create_token_tree (dfa, NULL, NULL, &br_token); + if (BE (work_tree == NULL, 0)) + goto parse_bracket_exp_espace; + } + return work_tree; + + parse_bracket_exp_espace: + *err = REG_ESPACE; + parse_bracket_exp_free_return: + re_free (sbcset); +#ifdef RE_ENABLE_I18N + free_charset (mbcset); +#endif /* RE_ENABLE_I18N */ + return NULL; +} + +/* Parse an element in the bracket expression. */ + +static reg_errcode_t +parse_bracket_element (bracket_elem_t *elem, re_string_t *regexp, + re_token_t *token, int token_len, re_dfa_t *dfa, + reg_syntax_t syntax, bool accept_hyphen) +{ +#ifdef RE_ENABLE_I18N + int cur_char_size; + cur_char_size = re_string_char_size_at (regexp, re_string_cur_idx (regexp)); + if (cur_char_size > 1) + { + elem->type = MB_CHAR; + elem->opr.wch = re_string_wchar_at (regexp, re_string_cur_idx (regexp)); + re_string_skip_bytes (regexp, cur_char_size); + return REG_NOERROR; + } +#endif /* RE_ENABLE_I18N */ + re_string_skip_bytes (regexp, token_len); /* Skip a token. */ + if (token->type == OP_OPEN_COLL_ELEM || token->type == OP_OPEN_CHAR_CLASS + || token->type == OP_OPEN_EQUIV_CLASS) + return parse_bracket_symbol (elem, regexp, token); + if (BE (token->type == OP_CHARSET_RANGE, 0) && !accept_hyphen) + { + /* A '-' must only appear as anything but a range indicator before + the closing bracket. Everything else is an error. */ + re_token_t token2; + (void) peek_token_bracket (&token2, regexp, syntax); + if (token2.type != OP_CLOSE_BRACKET) + /* The actual error value is not standardized since this whole + case is undefined. But ERANGE makes good sense. */ + return REG_ERANGE; + } + elem->type = SB_CHAR; + elem->opr.ch = token->opr.c; + return REG_NOERROR; +} + +/* Parse a bracket symbol in the bracket expression. Bracket symbols are + such as [::], [..], and + [==]. */ + +static reg_errcode_t +parse_bracket_symbol (bracket_elem_t *elem, re_string_t *regexp, + re_token_t *token) +{ + unsigned char ch, delim = token->opr.c; + int i = 0; + if (re_string_eoi(regexp)) + return REG_EBRACK; + for (;; ++i) + { + if (i >= BRACKET_NAME_BUF_SIZE) + return REG_EBRACK; + if (token->type == OP_OPEN_CHAR_CLASS) + ch = re_string_fetch_byte_case (regexp); + else + ch = re_string_fetch_byte (regexp); + if (re_string_eoi(regexp)) + return REG_EBRACK; + if (ch == delim && re_string_peek_byte (regexp, 0) == ']') + break; + elem->opr.name[i] = ch; + } + re_string_skip_bytes (regexp, 1); + elem->opr.name[i] = '\0'; + switch (token->type) + { + case OP_OPEN_COLL_ELEM: + elem->type = COLL_SYM; + break; + case OP_OPEN_EQUIV_CLASS: + elem->type = EQUIV_CLASS; + break; + case OP_OPEN_CHAR_CLASS: + elem->type = CHAR_CLASS; + break; + default: + break; + } + return REG_NOERROR; +} + + /* Helper function for parse_bracket_exp. + Build the equivalence class which is represented by NAME. + The result are written to MBCSET and SBCSET. + EQUIV_CLASS_ALLOC is the allocated size of mbcset->equiv_classes, + is a pointer argument sinse we may update it. */ + +static reg_errcode_t +#ifdef RE_ENABLE_I18N +build_equiv_class (bitset_t sbcset, re_charset_t *mbcset, + Idx *equiv_class_alloc, const unsigned char *name) +#else /* not RE_ENABLE_I18N */ +build_equiv_class (bitset_t sbcset, const unsigned char *name) +#endif /* not RE_ENABLE_I18N */ +{ +#ifdef _LIBC + uint32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES); + if (nrules != 0) + { + const int32_t *table, *indirect; + const unsigned char *weights, *extra, *cp; + unsigned char char_buf[2]; + int32_t idx1, idx2; + unsigned int ch; + size_t len; + /* This #include defines a local function! */ +# include + /* Calculate the index for equivalence class. */ + cp = name; + table = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB); + weights = (const unsigned char *) _NL_CURRENT (LC_COLLATE, + _NL_COLLATE_WEIGHTMB); + extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE, + _NL_COLLATE_EXTRAMB); + indirect = (const int32_t *) _NL_CURRENT (LC_COLLATE, + _NL_COLLATE_INDIRECTMB); + idx1 = findidx (&cp); + if (BE (idx1 == 0 || cp < name + strlen ((const char *) name), 0)) + /* This isn't a valid character. */ + return REG_ECOLLATE; + + /* Build single byte matcing table for this equivalence class. */ + char_buf[1] = (unsigned char) '\0'; + len = weights[idx1]; + for (ch = 0; ch < SBC_MAX; ++ch) + { + char_buf[0] = ch; + cp = char_buf; + idx2 = findidx (&cp); +/* + idx2 = table[ch]; +*/ + if (idx2 == 0) + /* This isn't a valid character. */ + continue; + if (len == weights[idx2]) + { + int cnt = 0; + while (cnt <= len && + weights[idx1 + 1 + cnt] == weights[idx2 + 1 + cnt]) + ++cnt; + + if (cnt > len) + bitset_set (sbcset, ch); + } + } + /* Check whether the array has enough space. */ + if (BE (*equiv_class_alloc == mbcset->nequiv_classes, 0)) + { + /* Not enough, realloc it. */ + /* +1 in case of mbcset->nequiv_classes is 0. */ + Idx new_equiv_class_alloc = 2 * mbcset->nequiv_classes + 1; + /* Use realloc since the array is NULL if *alloc == 0. */ + int32_t *new_equiv_classes = re_realloc (mbcset->equiv_classes, + int32_t, + new_equiv_class_alloc); + if (BE (new_equiv_classes == NULL, 0)) + return REG_ESPACE; + mbcset->equiv_classes = new_equiv_classes; + *equiv_class_alloc = new_equiv_class_alloc; + } + mbcset->equiv_classes[mbcset->nequiv_classes++] = idx1; + } + else +#endif /* _LIBC */ + { + if (BE (strlen ((const char *) name) != 1, 0)) + return REG_ECOLLATE; + bitset_set (sbcset, *name); + } + return REG_NOERROR; +} + + /* Helper function for parse_bracket_exp. + Build the character class which is represented by NAME. + The result are written to MBCSET and SBCSET. + CHAR_CLASS_ALLOC is the allocated size of mbcset->char_classes, + is a pointer argument sinse we may update it. */ + +static reg_errcode_t +#ifdef RE_ENABLE_I18N +build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset, + re_charset_t *mbcset, Idx *char_class_alloc, + const unsigned char *class_name, reg_syntax_t syntax) +#else /* not RE_ENABLE_I18N */ +build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset, + const unsigned char *class_name, reg_syntax_t syntax) +#endif /* not RE_ENABLE_I18N */ +{ + int i; + const char *name = (const char *) class_name; + + /* In case of REG_ICASE "upper" and "lower" match the both of + upper and lower cases. */ + if ((syntax & RE_ICASE) + && (strcmp (name, "upper") == 0 || strcmp (name, "lower") == 0)) + name = "alpha"; + +#ifdef RE_ENABLE_I18N + /* Check the space of the arrays. */ + if (BE (*char_class_alloc == mbcset->nchar_classes, 0)) + { + /* Not enough, realloc it. */ + /* +1 in case of mbcset->nchar_classes is 0. */ + Idx new_char_class_alloc = 2 * mbcset->nchar_classes + 1; + /* Use realloc since array is NULL if *alloc == 0. */ + wctype_t *new_char_classes = re_realloc (mbcset->char_classes, wctype_t, + new_char_class_alloc); + if (BE (new_char_classes == NULL, 0)) + return REG_ESPACE; + mbcset->char_classes = new_char_classes; + *char_class_alloc = new_char_class_alloc; + } + mbcset->char_classes[mbcset->nchar_classes++] = __wctype (name); +#endif /* RE_ENABLE_I18N */ + +#define BUILD_CHARCLASS_LOOP(ctype_func) \ + do { \ + if (BE (trans != NULL, 0)) \ + { \ + for (i = 0; i < SBC_MAX; ++i) \ + if (ctype_func (i)) \ + bitset_set (sbcset, trans[i]); \ + } \ + else \ + { \ + for (i = 0; i < SBC_MAX; ++i) \ + if (ctype_func (i)) \ + bitset_set (sbcset, i); \ + } \ + } while (0) + + if (strcmp (name, "alnum") == 0) + BUILD_CHARCLASS_LOOP (isalnum); + else if (strcmp (name, "cntrl") == 0) + BUILD_CHARCLASS_LOOP (iscntrl); + else if (strcmp (name, "lower") == 0) + BUILD_CHARCLASS_LOOP (islower); + else if (strcmp (name, "space") == 0) + BUILD_CHARCLASS_LOOP (isspace); + else if (strcmp (name, "alpha") == 0) + BUILD_CHARCLASS_LOOP (isalpha); + else if (strcmp (name, "digit") == 0) + BUILD_CHARCLASS_LOOP (isdigit); + else if (strcmp (name, "print") == 0) + BUILD_CHARCLASS_LOOP (isprint); + else if (strcmp (name, "upper") == 0) + BUILD_CHARCLASS_LOOP (isupper); + else if (strcmp (name, "blank") == 0) + BUILD_CHARCLASS_LOOP (isblank); + else if (strcmp (name, "graph") == 0) + BUILD_CHARCLASS_LOOP (isgraph); + else if (strcmp (name, "punct") == 0) + BUILD_CHARCLASS_LOOP (ispunct); + else if (strcmp (name, "xdigit") == 0) + BUILD_CHARCLASS_LOOP (isxdigit); + else + return REG_ECTYPE; + + return REG_NOERROR; +} + +static bin_tree_t * +build_charclass_op (re_dfa_t *dfa, RE_TRANSLATE_TYPE trans, + const unsigned char *class_name, + const unsigned char *extra, bool non_match, + reg_errcode_t *err) +{ + re_bitset_ptr_t sbcset; +#ifdef RE_ENABLE_I18N + re_charset_t *mbcset; + Idx alloc = 0; +#endif /* not RE_ENABLE_I18N */ + reg_errcode_t ret; + re_token_t br_token; + bin_tree_t *tree; + + sbcset = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1); +#ifdef RE_ENABLE_I18N + mbcset = (re_charset_t *) calloc (sizeof (re_charset_t), 1); +#endif /* RE_ENABLE_I18N */ + +#ifdef RE_ENABLE_I18N + if (BE (sbcset == NULL || mbcset == NULL, 0)) +#else /* not RE_ENABLE_I18N */ + if (BE (sbcset == NULL, 0)) +#endif /* not RE_ENABLE_I18N */ + { + *err = REG_ESPACE; + return NULL; + } + + if (non_match) + { +#ifdef RE_ENABLE_I18N + mbcset->non_match = 1; +#endif /* not RE_ENABLE_I18N */ + } + + /* We don't care the syntax in this case. */ + ret = build_charclass (trans, sbcset, +#ifdef RE_ENABLE_I18N + mbcset, &alloc, +#endif /* RE_ENABLE_I18N */ + class_name, 0); + + if (BE (ret != REG_NOERROR, 0)) + { + re_free (sbcset); +#ifdef RE_ENABLE_I18N + free_charset (mbcset); +#endif /* RE_ENABLE_I18N */ + *err = ret; + return NULL; + } + /* \w match '_' also. */ + for (; *extra; extra++) + bitset_set (sbcset, *extra); + + /* If it is non-matching list. */ + if (non_match) + bitset_not (sbcset); + +#ifdef RE_ENABLE_I18N + /* Ensure only single byte characters are set. */ + if (dfa->mb_cur_max > 1) + bitset_mask (sbcset, dfa->sb_char); +#endif + + /* Build a tree for simple bracket. */ + br_token.type = SIMPLE_BRACKET; + br_token.opr.sbcset = sbcset; + tree = create_token_tree (dfa, NULL, NULL, &br_token); + if (BE (tree == NULL, 0)) + goto build_word_op_espace; + +#ifdef RE_ENABLE_I18N + if (dfa->mb_cur_max > 1) + { + bin_tree_t *mbc_tree; + /* Build a tree for complex bracket. */ + br_token.type = COMPLEX_BRACKET; + br_token.opr.mbcset = mbcset; + dfa->has_mb_node = 1; + mbc_tree = create_token_tree (dfa, NULL, NULL, &br_token); + if (BE (mbc_tree == NULL, 0)) + goto build_word_op_espace; + /* Then join them by ALT node. */ + tree = create_tree (dfa, tree, mbc_tree, OP_ALT); + if (BE (mbc_tree != NULL, 1)) + return tree; + } + else + { + free_charset (mbcset); + return tree; + } +#else /* not RE_ENABLE_I18N */ + return tree; +#endif /* not RE_ENABLE_I18N */ + + build_word_op_espace: + re_free (sbcset); +#ifdef RE_ENABLE_I18N + free_charset (mbcset); +#endif /* RE_ENABLE_I18N */ + *err = REG_ESPACE; + return NULL; +} + +/* This is intended for the expressions like "a{1,3}". + Fetch a number from `input', and return the number. + Return REG_MISSING if the number field is empty like "{,1}". + Return REG_ERROR if an error occurred. */ + +static Idx +fetch_number (re_string_t *input, re_token_t *token, reg_syntax_t syntax) +{ + Idx num = REG_MISSING; + unsigned char c; + while (1) + { + fetch_token (token, input, syntax); + c = token->opr.c; + if (BE (token->type == END_OF_RE, 0)) + return REG_ERROR; + if (token->type == OP_CLOSE_DUP_NUM || c == ',') + break; + num = ((token->type != CHARACTER || c < '0' || '9' < c + || num == REG_ERROR) + ? REG_ERROR + : ((num == REG_MISSING) ? c - '0' : num * 10 + c - '0')); + num = (num > RE_DUP_MAX) ? REG_ERROR : num; + } + return num; +} + +#ifdef RE_ENABLE_I18N +static void +free_charset (re_charset_t *cset) +{ + re_free (cset->mbchars); +# ifdef _LIBC + re_free (cset->coll_syms); + re_free (cset->equiv_classes); + re_free (cset->range_starts); + re_free (cset->range_ends); +# endif + re_free (cset->char_classes); + re_free (cset); +} +#endif /* RE_ENABLE_I18N */ + +/* Functions for binary tree operation. */ + +/* Create a tree node. */ + +static bin_tree_t * +create_tree (re_dfa_t *dfa, bin_tree_t *left, bin_tree_t *right, + re_token_type_t type) +{ + re_token_t t; + t.type = type; + return create_token_tree (dfa, left, right, &t); +} + +static bin_tree_t * +create_token_tree (re_dfa_t *dfa, bin_tree_t *left, bin_tree_t *right, + const re_token_t *token) +{ + bin_tree_t *tree; + if (BE (dfa->str_tree_storage_idx == BIN_TREE_STORAGE_SIZE, 0)) + { + bin_tree_storage_t *storage = re_malloc (bin_tree_storage_t, 1); + + if (storage == NULL) + return NULL; + storage->next = dfa->str_tree_storage; + dfa->str_tree_storage = storage; + dfa->str_tree_storage_idx = 0; + } + tree = &dfa->str_tree_storage->data[dfa->str_tree_storage_idx++]; + + tree->parent = NULL; + tree->left = left; + tree->right = right; + tree->token = *token; + tree->token.duplicated = 0; + tree->token.opt_subexp = 0; + tree->first = NULL; + tree->next = NULL; + tree->node_idx = REG_MISSING; + + if (left != NULL) + left->parent = tree; + if (right != NULL) + right->parent = tree; + return tree; +} + +/* Mark the tree SRC as an optional subexpression. + To be called from preorder or postorder. */ + +static reg_errcode_t +mark_opt_subexp (void *extra, bin_tree_t *node) +{ + Idx idx = (Idx) (long) extra; + if (node->token.type == SUBEXP && node->token.opr.idx == idx) + node->token.opt_subexp = 1; + + return REG_NOERROR; +} + +/* Free the allocated memory inside NODE. */ + +static void +free_token (re_token_t *node) +{ +#ifdef RE_ENABLE_I18N + if (node->type == COMPLEX_BRACKET && node->duplicated == 0) + free_charset (node->opr.mbcset); + else +#endif /* RE_ENABLE_I18N */ + if (node->type == SIMPLE_BRACKET && node->duplicated == 0) + re_free (node->opr.sbcset); +} + +/* Worker function for tree walking. Free the allocated memory inside NODE + and its children. */ + +static reg_errcode_t +free_tree (void *extra, bin_tree_t *node) +{ + free_token (&node->token); + return REG_NOERROR; +} + + +/* Duplicate the node SRC, and return new node. This is a preorder + visit similar to the one implemented by the generic visitor, but + we need more infrastructure to maintain two parallel trees --- so, + it's easier to duplicate. */ + +static bin_tree_t * +duplicate_tree (const bin_tree_t *root, re_dfa_t *dfa) +{ + const bin_tree_t *node; + bin_tree_t *dup_root; + bin_tree_t **p_new = &dup_root, *dup_node = root->parent; + + for (node = root; ; ) + { + /* Create a new tree and link it back to the current parent. */ + *p_new = create_token_tree (dfa, NULL, NULL, &node->token); + if (*p_new == NULL) + return NULL; + (*p_new)->parent = dup_node; + (*p_new)->token.duplicated = 1; + dup_node = *p_new; + + /* Go to the left node, or up and to the right. */ + if (node->left) + { + node = node->left; + p_new = &dup_node->left; + } + else + { + const bin_tree_t *prev = NULL; + while (node->right == prev || node->right == NULL) + { + prev = node; + node = node->parent; + dup_node = dup_node->parent; + if (!node) + return dup_root; + } + node = node->right; + p_new = &dup_node->right; + } + } +} diff --git a/src/bin/findutils/gnulib/lib/regex.c b/src/bin/findutils/gnulib/lib/regex.c new file mode 100644 index 0000000000..ee36378a63 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/regex.c @@ -0,0 +1,71 @@ +/* Extended regular expression matching and search library. + Copyright (C) 2002, 2003, 2005, 2006 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Isamu Hasegawa . + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#include + +/* Make sure noone compiles this code with a C++ compiler. */ +#if defined __cplusplus && defined _LIBC +# error "This is C code, use a C compiler" +#endif + +#ifdef _LIBC +/* We have to keep the namespace clean. */ +# define regfree(preg) __regfree (preg) +# define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef) +# define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags) +# define regerror(errcode, preg, errbuf, errbuf_size) \ + __regerror(errcode, preg, errbuf, errbuf_size) +# define re_set_registers(bu, re, nu, st, en) \ + __re_set_registers (bu, re, nu, st, en) +# define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \ + __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop) +# define re_match(bufp, string, size, pos, regs) \ + __re_match (bufp, string, size, pos, regs) +# define re_search(bufp, string, size, startpos, range, regs) \ + __re_search (bufp, string, size, startpos, range, regs) +# define re_compile_pattern(pattern, length, bufp) \ + __re_compile_pattern (pattern, length, bufp) +# define re_set_syntax(syntax) __re_set_syntax (syntax) +# define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \ + __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop) +# define re_compile_fastmap(bufp) __re_compile_fastmap (bufp) + +# include "../locale/localeinfo.h" +#endif + +/* On some systems, limits.h sets RE_DUP_MAX to a lower value than + GNU regex allows. Include it before , which correctly + #undefs RE_DUP_MAX and sets it to the right value. */ +#include + +#include +#include "regex_internal.h" + +#include "regex_internal.c" +#include "regcomp.c" +#include "regexec.c" + +/* Binary backward compatibility. */ +#if _LIBC +# include +# if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_3) +link_warning (re_max_failures, "the 're_max_failures' variable is obsolete and will go away.") +int re_max_failures = 2000; +# endif +#endif diff --git a/src/bin/findutils/gnulib/lib/regex.h b/src/bin/findutils/gnulib/lib/regex.h new file mode 100644 index 0000000000..a53128325a --- /dev/null +++ b/src/bin/findutils/gnulib/lib/regex.h @@ -0,0 +1,675 @@ +/* Definitions for data structures and routines for the regular + expression library. + Copyright (C) 1985,1989-93,1995-98,2000,2001,2002,2003,2005,2006 + Free Software Foundation, Inc. + This file is part of the GNU C Library. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _REGEX_H +#define _REGEX_H 1 + +#include + +/* Allow the use in C++ code. */ +#ifdef __cplusplus +extern "C" { +#endif + +/* Define __USE_GNU_REGEX to declare GNU extensions that violate the + POSIX name space rules. */ +#undef __USE_GNU_REGEX +#if (defined _GNU_SOURCE \ + || (!defined _POSIX_C_SOURCE && !defined _POSIX_SOURCE \ + && !defined _XOPEN_SOURCE)) +# define __USE_GNU_REGEX 1 +#endif + +#ifdef _REGEX_LARGE_OFFSETS + +/* Use types and values that are wide enough to represent signed and + unsigned byte offsets in memory. This currently works only when + the regex code is used outside of the GNU C library; it is not yet + supported within glibc itself, and glibc users should not define + _REGEX_LARGE_OFFSETS. */ + +/* The type of the offset of a byte within a string. + For historical reasons POSIX 1003.1-2004 requires that regoff_t be + at least as wide as off_t. However, many common POSIX platforms set + regoff_t to the more-sensible ssize_t and the Open Group has + signalled its intention to change the requirement to be that + regoff_t be at least as wide as ptrdiff_t and ssize_t; see XBD ERN + 60 (2005-08-25). We don't know of any hosts where ssize_t or + ptrdiff_t is wider than ssize_t, so ssize_t is safe. */ +typedef ssize_t regoff_t; + +/* The type of nonnegative object indexes. Traditionally, GNU regex + uses 'int' for these. Code that uses __re_idx_t should work + regardless of whether the type is signed. */ +typedef size_t __re_idx_t; + +/* The type of object sizes. */ +typedef size_t __re_size_t; + +/* The type of object sizes, in places where the traditional code + uses unsigned long int. */ +typedef size_t __re_long_size_t; + +#else + +/* Use types that are binary-compatible with the traditional GNU regex + implementation, which mishandles strings longer than INT_MAX. */ + +typedef int regoff_t; +typedef int __re_idx_t; +typedef unsigned int __re_size_t; +typedef unsigned long int __re_long_size_t; + +#endif + +/* The following two types have to be signed and unsigned integer type + wide enough to hold a value of a pointer. For most ANSI compilers + ptrdiff_t and size_t should be likely OK. Still size of these two + types is 2 for Microsoft C. Ugh... */ +typedef long int s_reg_t; +typedef unsigned long int active_reg_t; + +/* The following bits are used to determine the regexp syntax we + recognize. The set/not-set meanings are chosen so that Emacs syntax + remains the value 0. The bits are given in alphabetical order, and + the definitions shifted by one from the previous bit; thus, when we + add or remove a bit, only one other definition need change. */ +typedef unsigned long int reg_syntax_t; + +#ifdef __USE_GNU_REGEX + +/* If this bit is not set, then \ inside a bracket expression is literal. + If set, then such a \ quotes the following character. */ +# define RE_BACKSLASH_ESCAPE_IN_LISTS ((unsigned long int) 1) + +/* If this bit is not set, then + and ? are operators, and \+ and \? are + literals. + If set, then \+ and \? are operators and + and ? are literals. */ +# define RE_BK_PLUS_QM (RE_BACKSLASH_ESCAPE_IN_LISTS << 1) + +/* If this bit is set, then character classes are supported. They are: + [:alpha:], [:upper:], [:lower:], [:digit:], [:alnum:], [:xdigit:], + [:space:], [:print:], [:punct:], [:graph:], and [:cntrl:]. + If not set, then character classes are not supported. */ +# define RE_CHAR_CLASSES (RE_BK_PLUS_QM << 1) + +/* If this bit is set, then ^ and $ are always anchors (outside bracket + expressions, of course). + If this bit is not set, then it depends: + ^ is an anchor if it is at the beginning of a regular + expression or after an open-group or an alternation operator; + $ is an anchor if it is at the end of a regular expression, or + before a close-group or an alternation operator. + + This bit could be (re)combined with RE_CONTEXT_INDEP_OPS, because + POSIX draft 11.2 says that * etc. in leading positions is undefined. + We already implemented a previous draft which made those constructs + invalid, though, so we haven't changed the code back. */ +# define RE_CONTEXT_INDEP_ANCHORS (RE_CHAR_CLASSES << 1) + +/* If this bit is set, then special characters are always special + regardless of where they are in the pattern. + If this bit is not set, then special characters are special only in + some contexts; otherwise they are ordinary. Specifically, + * + ? and intervals are only special when not after the beginning, + open-group, or alternation operator. */ +# define RE_CONTEXT_INDEP_OPS (RE_CONTEXT_INDEP_ANCHORS << 1) + +/* If this bit is set, then *, +, ?, and { cannot be first in an re or + immediately after an alternation or begin-group operator. */ +# define RE_CONTEXT_INVALID_OPS (RE_CONTEXT_INDEP_OPS << 1) + +/* If this bit is set, then . matches newline. + If not set, then it doesn't. */ +# define RE_DOT_NEWLINE (RE_CONTEXT_INVALID_OPS << 1) + +/* If this bit is set, then . doesn't match NUL. + If not set, then it does. */ +# define RE_DOT_NOT_NULL (RE_DOT_NEWLINE << 1) + +/* If this bit is set, nonmatching lists [^...] do not match newline. + If not set, they do. */ +# define RE_HAT_LISTS_NOT_NEWLINE (RE_DOT_NOT_NULL << 1) + +/* If this bit is set, either \{...\} or {...} defines an + interval, depending on RE_NO_BK_BRACES. + If not set, \{, \}, {, and } are literals. */ +# define RE_INTERVALS (RE_HAT_LISTS_NOT_NEWLINE << 1) + +/* If this bit is set, +, ? and | aren't recognized as operators. + If not set, they are. */ +# define RE_LIMITED_OPS (RE_INTERVALS << 1) + +/* If this bit is set, newline is an alternation operator. + If not set, newline is literal. */ +# define RE_NEWLINE_ALT (RE_LIMITED_OPS << 1) + +/* If this bit is set, then `{...}' defines an interval, and \{ and \} + are literals. + If not set, then `\{...\}' defines an interval. */ +# define RE_NO_BK_BRACES (RE_NEWLINE_ALT << 1) + +/* If this bit is set, (...) defines a group, and \( and \) are literals. + If not set, \(...\) defines a group, and ( and ) are literals. */ +# define RE_NO_BK_PARENS (RE_NO_BK_BRACES << 1) + +/* If this bit is set, then \ matches . + If not set, then \ is a back-reference. */ +# define RE_NO_BK_REFS (RE_NO_BK_PARENS << 1) + +/* If this bit is set, then | is an alternation operator, and \| is literal. + If not set, then \| is an alternation operator, and | is literal. */ +# define RE_NO_BK_VBAR (RE_NO_BK_REFS << 1) + +/* If this bit is set, then an ending range point collating higher + than the starting range point, as in [z-a], is invalid. + If not set, then when ending range point collates higher than the + starting range point, the range is ignored. */ +# define RE_NO_EMPTY_RANGES (RE_NO_BK_VBAR << 1) + +/* If this bit is set, then an unmatched ) is ordinary. + If not set, then an unmatched ) is invalid. */ +# define RE_UNMATCHED_RIGHT_PAREN_ORD (RE_NO_EMPTY_RANGES << 1) + +/* If this bit is set, succeed as soon as we match the whole pattern, + without further backtracking. */ +# define RE_NO_POSIX_BACKTRACKING (RE_UNMATCHED_RIGHT_PAREN_ORD << 1) + +/* If this bit is set, do not process the GNU regex operators. + If not set, then the GNU regex operators are recognized. */ +# define RE_NO_GNU_OPS (RE_NO_POSIX_BACKTRACKING << 1) + +/* If this bit is set, turn on internal regex debugging. + If not set, and debugging was on, turn it off. + This only works if regex.c is compiled -DDEBUG. + We define this bit always, so that all that's needed to turn on + debugging is to recompile regex.c; the calling code can always have + this bit set, and it won't affect anything in the normal case. */ +# define RE_DEBUG (RE_NO_GNU_OPS << 1) + +/* If this bit is set, a syntactically invalid interval is treated as + a string of ordinary characters. For example, the ERE 'a{1' is + treated as 'a\{1'. */ +# define RE_INVALID_INTERVAL_ORD (RE_DEBUG << 1) + +/* If this bit is set, then ignore case when matching. + If not set, then case is significant. */ +# define RE_ICASE (RE_INVALID_INTERVAL_ORD << 1) + +/* This bit is used internally like RE_CONTEXT_INDEP_ANCHORS but only + for ^, because it is difficult to scan the regex backwards to find + whether ^ should be special. */ +# define RE_CARET_ANCHORS_HERE (RE_ICASE << 1) + +/* If this bit is set, then \{ cannot be first in an bre or + immediately after an alternation or begin-group operator. */ +# define RE_CONTEXT_INVALID_DUP (RE_CARET_ANCHORS_HERE << 1) + +/* If this bit is set, then no_sub will be set to 1 during + re_compile_pattern. */ +# define RE_NO_SUB (RE_CONTEXT_INVALID_DUP << 1) + +#endif /* defined __USE_GNU_REGEX */ + +/* This global variable defines the particular regexp syntax to use (for + some interfaces). When a regexp is compiled, the syntax used is + stored in the pattern buffer, so changing this does not affect + already-compiled regexps. */ +extern reg_syntax_t re_syntax_options; + +#ifdef __USE_GNU_REGEX +/* Define combinations of the above bits for the standard possibilities. + (The [[[ comments delimit what gets put into the Texinfo file, so + don't delete them!) */ +/* [[[begin syntaxes]]] */ +# define RE_SYNTAX_EMACS 0 + +# define RE_SYNTAX_AWK \ + (RE_BACKSLASH_ESCAPE_IN_LISTS | RE_DOT_NOT_NULL \ + | RE_NO_BK_PARENS | RE_NO_BK_REFS \ + | RE_NO_BK_VBAR | RE_NO_EMPTY_RANGES \ + | RE_DOT_NEWLINE | RE_CONTEXT_INDEP_ANCHORS \ + | RE_UNMATCHED_RIGHT_PAREN_ORD | RE_NO_GNU_OPS) + +# define RE_SYNTAX_GNU_AWK \ + ((RE_SYNTAX_POSIX_EXTENDED | RE_BACKSLASH_ESCAPE_IN_LISTS | RE_DEBUG) \ + & ~(RE_DOT_NOT_NULL | RE_INTERVALS | RE_CONTEXT_INDEP_OPS \ + | RE_CONTEXT_INVALID_OPS )) + +# define RE_SYNTAX_POSIX_AWK \ + (RE_SYNTAX_POSIX_EXTENDED | RE_BACKSLASH_ESCAPE_IN_LISTS \ + | RE_INTERVALS | RE_NO_GNU_OPS) + +# define RE_SYNTAX_GREP \ + (RE_BK_PLUS_QM | RE_CHAR_CLASSES \ + | RE_HAT_LISTS_NOT_NEWLINE | RE_INTERVALS \ + | RE_NEWLINE_ALT) + +# define RE_SYNTAX_EGREP \ + (RE_CHAR_CLASSES | RE_CONTEXT_INDEP_ANCHORS \ + | RE_CONTEXT_INDEP_OPS | RE_HAT_LISTS_NOT_NEWLINE \ + | RE_NEWLINE_ALT | RE_NO_BK_PARENS \ + | RE_NO_BK_VBAR) + +# define RE_SYNTAX_POSIX_EGREP \ + (RE_SYNTAX_EGREP | RE_INTERVALS | RE_NO_BK_BRACES \ + | RE_INVALID_INTERVAL_ORD) + +/* P1003.2/D11.2, section 4.20.7.1, lines 5078ff. */ +# define RE_SYNTAX_ED RE_SYNTAX_POSIX_BASIC + +# define RE_SYNTAX_SED RE_SYNTAX_POSIX_BASIC + +/* Syntax bits common to both basic and extended POSIX regex syntax. */ +# define _RE_SYNTAX_POSIX_COMMON \ + (RE_CHAR_CLASSES | RE_DOT_NEWLINE | RE_DOT_NOT_NULL \ + | RE_INTERVALS | RE_NO_EMPTY_RANGES) + +# define RE_SYNTAX_POSIX_BASIC \ + (_RE_SYNTAX_POSIX_COMMON | RE_BK_PLUS_QM | RE_CONTEXT_INVALID_DUP) + +/* Differs from ..._POSIX_BASIC only in that RE_BK_PLUS_QM becomes + RE_LIMITED_OPS, i.e., \? \+ \| are not recognized. Actually, this + isn't minimal, since other operators, such as \`, aren't disabled. */ +# define RE_SYNTAX_POSIX_MINIMAL_BASIC \ + (_RE_SYNTAX_POSIX_COMMON | RE_LIMITED_OPS) + +# define RE_SYNTAX_POSIX_EXTENDED \ + (_RE_SYNTAX_POSIX_COMMON | RE_CONTEXT_INDEP_ANCHORS \ + | RE_CONTEXT_INDEP_OPS | RE_NO_BK_BRACES \ + | RE_NO_BK_PARENS | RE_NO_BK_VBAR \ + | RE_CONTEXT_INVALID_OPS | RE_UNMATCHED_RIGHT_PAREN_ORD) + +/* Differs from ..._POSIX_EXTENDED in that RE_CONTEXT_INDEP_OPS is + removed and RE_NO_BK_REFS is added. */ +# define RE_SYNTAX_POSIX_MINIMAL_EXTENDED \ + (_RE_SYNTAX_POSIX_COMMON | RE_CONTEXT_INDEP_ANCHORS \ + | RE_CONTEXT_INVALID_OPS | RE_NO_BK_BRACES \ + | RE_NO_BK_PARENS | RE_NO_BK_REFS \ + | RE_NO_BK_VBAR | RE_UNMATCHED_RIGHT_PAREN_ORD) +/* [[[end syntaxes]]] */ + +#endif /* defined __USE_GNU_REGEX */ + +#ifdef __USE_GNU_REGEX + +/* Maximum number of duplicates an interval can allow. POSIX-conforming + systems might define this in , but we want our + value, so remove any previous define. */ +# ifdef RE_DUP_MAX +# undef RE_DUP_MAX +# endif + +/* RE_DUP_MAX is 2**15 - 1 because an earlier implementation stored + the counter as a 2-byte signed integer. This is no longer true, so + RE_DUP_MAX could be increased to (INT_MAX / 10 - 1), or to + ((SIZE_MAX - 2) / 10 - 1) if _REGEX_LARGE_OFFSETS is defined. + However, there would be a huge performance problem if someone + actually used a pattern like a\{214748363\}, so RE_DUP_MAX retains + its historical value. */ +# define RE_DUP_MAX (0x7fff) + +#endif /* defined __USE_GNU_REGEX */ + + +/* POSIX `cflags' bits (i.e., information for `regcomp'). */ + +/* If this bit is set, then use extended regular expression syntax. + If not set, then use basic regular expression syntax. */ +#define REG_EXTENDED 1 + +/* If this bit is set, then ignore case when matching. + If not set, then case is significant. */ +#define REG_ICASE (1 << 1) + +/* If this bit is set, then anchors do not match at newline + characters in the string. + If not set, then anchors do match at newlines. */ +#define REG_NEWLINE (1 << 2) + +/* If this bit is set, then report only success or fail in regexec. + If not set, then returns differ between not matching and errors. */ +#define REG_NOSUB (1 << 3) + + +/* POSIX `eflags' bits (i.e., information for regexec). */ + +/* If this bit is set, then the beginning-of-line operator doesn't match + the beginning of the string (presumably because it's not the + beginning of a line). + If not set, then the beginning-of-line operator does match the + beginning of the string. */ +#define REG_NOTBOL 1 + +/* Like REG_NOTBOL, except for the end-of-line. */ +#define REG_NOTEOL (1 << 1) + +/* Use PMATCH[0] to delimit the start and end of the search in the + buffer. */ +#define REG_STARTEND (1 << 2) + + +/* If any error codes are removed, changed, or added, update the + `__re_error_msgid' table in regcomp.c. */ + +typedef enum +{ + _REG_ENOSYS = -1, /* This will never happen for this implementation. */ + _REG_NOERROR = 0, /* Success. */ + _REG_NOMATCH, /* Didn't find a match (for regexec). */ + + /* POSIX regcomp return error codes. (In the order listed in the + standard.) */ + _REG_BADPAT, /* Invalid pattern. */ + _REG_ECOLLATE, /* Invalid collating element. */ + _REG_ECTYPE, /* Invalid character class name. */ + _REG_EESCAPE, /* Trailing backslash. */ + _REG_ESUBREG, /* Invalid back reference. */ + _REG_EBRACK, /* Unmatched left bracket. */ + _REG_EPAREN, /* Parenthesis imbalance. */ + _REG_EBRACE, /* Unmatched \{. */ + _REG_BADBR, /* Invalid contents of \{\}. */ + _REG_ERANGE, /* Invalid range end. */ + _REG_ESPACE, /* Ran out of memory. */ + _REG_BADRPT, /* No preceding re for repetition op. */ + + /* Error codes we've added. */ + _REG_EEND, /* Premature end. */ + _REG_ESIZE, /* Compiled pattern bigger than 2^16 bytes. */ + _REG_ERPAREN /* Unmatched ) or \); not returned from regcomp. */ +} reg_errcode_t; + +#ifdef _XOPEN_SOURCE +# define REG_ENOSYS _REG_ENOSYS +#endif +#define REG_NOERROR _REG_NOERROR +#define REG_NOMATCH _REG_NOMATCH +#define REG_BADPAT _REG_BADPAT +#define REG_ECOLLATE _REG_ECOLLATE +#define REG_ECTYPE _REG_ECTYPE +#define REG_EESCAPE _REG_EESCAPE +#define REG_ESUBREG _REG_ESUBREG +#define REG_EBRACK _REG_EBRACK +#define REG_EPAREN _REG_EPAREN +#define REG_EBRACE _REG_EBRACE +#define REG_BADBR _REG_BADBR +#define REG_ERANGE _REG_ERANGE +#define REG_ESPACE _REG_ESPACE +#define REG_BADRPT _REG_BADRPT +#define REG_EEND _REG_EEND +#define REG_ESIZE _REG_ESIZE +#define REG_ERPAREN _REG_ERPAREN + +/* struct re_pattern_buffer normally uses member names like `buffer' + that POSIX does not allow. In POSIX mode these members have names + with leading `re_' (e.g., `re_buffer'). */ +#ifdef __USE_GNU_REGEX +# define _REG_RE_NAME(id) id +# define _REG_RM_NAME(id) id +#else +# define _REG_RE_NAME(id) re_##id +# define _REG_RM_NAME(id) rm_##id +#endif + +/* The user can specify the type of the re_translate member by + defining the macro RE_TRANSLATE_TYPE, which defaults to unsigned + char *. This pollutes the POSIX name space, so in POSIX mode just + use unsigned char *. */ +#ifdef __USE_GNU_REGEX +# ifndef RE_TRANSLATE_TYPE +# define RE_TRANSLATE_TYPE unsigned char * +# endif +# define REG_TRANSLATE_TYPE RE_TRANSLATE_TYPE +#else +# define REG_TRANSLATE_TYPE unsigned char * +#endif + +/* This data structure represents a compiled pattern. Before calling + the pattern compiler, the fields `buffer', `allocated', `fastmap', + `translate', and `no_sub' can be set. After the pattern has been + compiled, the `re_nsub' field is available. All other fields are + private to the regex routines. */ + +struct re_pattern_buffer +{ + /* Space that holds the compiled pattern. It is declared as + `unsigned char *' because its elements are sometimes used as + array indexes. */ + unsigned char *_REG_RE_NAME (buffer); + + /* Number of bytes to which `buffer' points. */ + __re_long_size_t _REG_RE_NAME (allocated); + + /* Number of bytes actually used in `buffer'. */ + __re_long_size_t _REG_RE_NAME (used); + + /* Syntax setting with which the pattern was compiled. */ + reg_syntax_t _REG_RE_NAME (syntax); + + /* Pointer to a fastmap, if any, otherwise zero. re_search uses the + fastmap, if there is one, to skip over impossible starting points + for matches. */ + char *_REG_RE_NAME (fastmap); + + /* Either a translate table to apply to all characters before + comparing them, or zero for no translation. The translation is + applied to a pattern when it is compiled and to a string when it + is matched. */ + REG_TRANSLATE_TYPE _REG_RE_NAME (translate); + + /* Number of subexpressions found by the compiler. */ + size_t re_nsub; + + /* Zero if this pattern cannot match the empty string, one else. + Well, in truth it's used only in `re_search_2', to see whether or + not we should use the fastmap, so we don't set this absolutely + perfectly; see `re_compile_fastmap' (the `duplicate' case). */ + unsigned int _REG_RE_NAME (can_be_null) : 1; + + /* If REGS_UNALLOCATED, allocate space in the `regs' structure + for `max (RE_NREGS, re_nsub + 1)' groups. + If REGS_REALLOCATE, reallocate space if necessary. + If REGS_FIXED, use what's there. */ +#ifdef __USE_GNU_REGEX +# define REGS_UNALLOCATED 0 +# define REGS_REALLOCATE 1 +# define REGS_FIXED 2 +#endif + unsigned int _REG_RE_NAME (regs_allocated) : 2; + + /* Set to zero when `regex_compile' compiles a pattern; set to one + by `re_compile_fastmap' if it updates the fastmap. */ + unsigned int _REG_RE_NAME (fastmap_accurate) : 1; + + /* If set, `re_match_2' does not return information about + subexpressions. */ + unsigned int _REG_RE_NAME (no_sub) : 1; + + /* If set, a beginning-of-line anchor doesn't match at the beginning + of the string. */ + unsigned int _REG_RE_NAME (not_bol) : 1; + + /* Similarly for an end-of-line anchor. */ + unsigned int _REG_RE_NAME (not_eol) : 1; + + /* If true, an anchor at a newline matches. */ + unsigned int _REG_RE_NAME (newline_anchor) : 1; + +/* [[[end pattern_buffer]]] */ +}; + +typedef struct re_pattern_buffer regex_t; + +/* This is the structure we store register match data in. See + regex.texinfo for a full description of what registers match. */ +struct re_registers +{ + __re_size_t _REG_RM_NAME (num_regs); + regoff_t *_REG_RM_NAME (start); + regoff_t *_REG_RM_NAME (end); +}; + + +/* If `regs_allocated' is REGS_UNALLOCATED in the pattern buffer, + `re_match_2' returns information about at least this many registers + the first time a `regs' structure is passed. */ +#if !defined RE_NREGS && defined __USE_GNU_REGEX +# define RE_NREGS 30 +#endif + + +/* POSIX specification for registers. Aside from the different names than + `re_registers', POSIX uses an array of structures, instead of a + structure of arrays. */ +typedef struct +{ + regoff_t rm_so; /* Byte offset from string's start to substring's start. */ + regoff_t rm_eo; /* Byte offset from string's start to substring's end. */ +} regmatch_t; + +/* Declarations for routines. */ + +/* Sets the current default syntax to SYNTAX, and return the old syntax. + You can also simply assign to the `re_syntax_options' variable. */ +extern reg_syntax_t re_set_syntax (reg_syntax_t __syntax); + +/* Compile the regular expression PATTERN, with length LENGTH + and syntax given by the global `re_syntax_options', into the buffer + BUFFER. Return NULL if successful, and an error string if not. */ +extern const char *re_compile_pattern (const char *__pattern, size_t __length, + struct re_pattern_buffer *__buffer); + + +/* Compile a fastmap for the compiled pattern in BUFFER; used to + accelerate searches. Return 0 if successful and -2 if was an + internal error. */ +extern int re_compile_fastmap (struct re_pattern_buffer *__buffer); + + +/* Search in the string STRING (with length LENGTH) for the pattern + compiled into BUFFER. Start searching at position START, for RANGE + characters. Return the starting position of the match, -1 for no + match, or -2 for an internal error. Also return register + information in REGS (if REGS and BUFFER->no_sub are nonzero). */ +extern regoff_t re_search (struct re_pattern_buffer *__buffer, + const char *__string, __re_idx_t __length, + __re_idx_t __start, regoff_t __range, + struct re_registers *__regs); + + +/* Like `re_search', but search in the concatenation of STRING1 and + STRING2. Also, stop searching at index START + STOP. */ +extern regoff_t re_search_2 (struct re_pattern_buffer *__buffer, + const char *__string1, __re_idx_t __length1, + const char *__string2, __re_idx_t __length2, + __re_idx_t __start, regoff_t __range, + struct re_registers *__regs, + __re_idx_t __stop); + + +/* Like `re_search', but return how many characters in STRING the regexp + in BUFFER matched, starting at position START. */ +extern regoff_t re_match (struct re_pattern_buffer *__buffer, + const char *__string, __re_idx_t __length, + __re_idx_t __start, struct re_registers *__regs); + + +/* Relates to `re_match' as `re_search_2' relates to `re_search'. */ +extern regoff_t re_match_2 (struct re_pattern_buffer *__buffer, + const char *__string1, __re_idx_t __length1, + const char *__string2, __re_idx_t __length2, + __re_idx_t __start, struct re_registers *__regs, + __re_idx_t __stop); + + +/* Set REGS to hold NUM_REGS registers, storing them in STARTS and + ENDS. Subsequent matches using BUFFER and REGS will use this memory + for recording register information. STARTS and ENDS must be + allocated with malloc, and must each be at least `NUM_REGS * sizeof + (regoff_t)' bytes long. + + If NUM_REGS == 0, then subsequent matches should allocate their own + register data. + + Unless this function is called, the first search or match using + PATTERN_BUFFER will allocate its own register data, without + freeing the old data. */ +extern void re_set_registers (struct re_pattern_buffer *__buffer, + struct re_registers *__regs, + __re_size_t __num_regs, + regoff_t *__starts, regoff_t *__ends); + +#if defined _REGEX_RE_COMP || defined _LIBC +# ifndef _CRAY +/* 4.2 bsd compatibility. */ +extern char *re_comp (const char *); +extern int re_exec (const char *); +# endif +#endif + +/* GCC 2.95 and later have "__restrict"; C99 compilers have + "restrict", and "configure" may have defined "restrict". + Other compilers use __restrict, __restrict__, and _Restrict, and + 'configure' might #define 'restrict' to those words, so pick a + different name. */ +#ifndef _Restrict_ +# if 199901L <= __STDC_VERSION__ +# define _Restrict_ restrict +# elif 2 < __GNUC__ || (2 == __GNUC__ && 95 <= __GNUC_MINOR__) +# define _Restrict_ __restrict +# else +# define _Restrict_ +# endif +#endif +/* gcc 3.1 and up support the [restrict] syntax. Don't trust + sys/cdefs.h's definition of __restrict_arr, though, as it + mishandles gcc -ansi -pedantic. */ +#ifndef _Restrict_arr_ +# if ((199901L <= __STDC_VERSION__ \ + || ((3 < __GNUC__ || (3 == __GNUC__ && 1 <= __GNUC_MINOR__)) \ + && !__STRICT_ANSI__)) \ + && !defined __GNUG__) +# define _Restrict_arr_ _Restrict_ +# else +# define _Restrict_arr_ +# endif +#endif + +/* POSIX compatibility. */ +extern int regcomp (regex_t *_Restrict_ __preg, + const char *_Restrict_ __pattern, + int __cflags); + +extern int regexec (const regex_t *_Restrict_ __preg, + const char *_Restrict_ __string, size_t __nmatch, + regmatch_t __pmatch[_Restrict_arr_], + int __eflags); + +extern size_t regerror (int __errcode, const regex_t *_Restrict_ __preg, + char *_Restrict_ __errbuf, size_t __errbuf_size); + +extern void regfree (regex_t *__preg); + + +#ifdef __cplusplus +} +#endif /* C++ */ + +#endif /* regex.h */ diff --git a/src/bin/findutils/gnulib/lib/regex_internal.c b/src/bin/findutils/gnulib/lib/regex_internal.c new file mode 100644 index 0000000000..cf3bf1bb93 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/regex_internal.c @@ -0,0 +1,1741 @@ +/* Extended regular expression matching and search library. + Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 Free Software + Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Isamu Hasegawa . + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +static void re_string_construct_common (const char *str, Idx len, + re_string_t *pstr, + RE_TRANSLATE_TYPE trans, bool icase, + const re_dfa_t *dfa) internal_function; +static re_dfastate_t *create_ci_newstate (const re_dfa_t *dfa, + const re_node_set *nodes, + re_hashval_t hash) internal_function; +static re_dfastate_t *create_cd_newstate (const re_dfa_t *dfa, + const re_node_set *nodes, + unsigned int context, + re_hashval_t hash) internal_function; + +/* Functions for string operation. */ + +/* This function allocate the buffers. It is necessary to call + re_string_reconstruct before using the object. */ + +static reg_errcode_t +internal_function +re_string_allocate (re_string_t *pstr, const char *str, Idx len, Idx init_len, + RE_TRANSLATE_TYPE trans, bool icase, const re_dfa_t *dfa) +{ + reg_errcode_t ret; + Idx init_buf_len; + + /* Ensure at least one character fits into the buffers. */ + if (init_len < dfa->mb_cur_max) + init_len = dfa->mb_cur_max; + init_buf_len = (len + 1 < init_len) ? len + 1: init_len; + re_string_construct_common (str, len, pstr, trans, icase, dfa); + + ret = re_string_realloc_buffers (pstr, init_buf_len); + if (BE (ret != REG_NOERROR, 0)) + return ret; + + pstr->word_char = dfa->word_char; + pstr->word_ops_used = dfa->word_ops_used; + pstr->mbs = pstr->mbs_allocated ? pstr->mbs : (unsigned char *) str; + pstr->valid_len = (pstr->mbs_allocated || dfa->mb_cur_max > 1) ? 0 : len; + pstr->valid_raw_len = pstr->valid_len; + return REG_NOERROR; +} + +/* This function allocate the buffers, and initialize them. */ + +static reg_errcode_t +internal_function +re_string_construct (re_string_t *pstr, const char *str, Idx len, + RE_TRANSLATE_TYPE trans, bool icase, const re_dfa_t *dfa) +{ + reg_errcode_t ret; + memset (pstr, '\0', sizeof (re_string_t)); + re_string_construct_common (str, len, pstr, trans, icase, dfa); + + if (len > 0) + { + ret = re_string_realloc_buffers (pstr, len + 1); + if (BE (ret != REG_NOERROR, 0)) + return ret; + } + pstr->mbs = pstr->mbs_allocated ? pstr->mbs : (unsigned char *) str; + + if (icase) + { +#ifdef RE_ENABLE_I18N + if (dfa->mb_cur_max > 1) + { + while (1) + { + ret = build_wcs_upper_buffer (pstr); + if (BE (ret != REG_NOERROR, 0)) + return ret; + if (pstr->valid_raw_len >= len) + break; + if (pstr->bufs_len > pstr->valid_len + dfa->mb_cur_max) + break; + ret = re_string_realloc_buffers (pstr, pstr->bufs_len * 2); + if (BE (ret != REG_NOERROR, 0)) + return ret; + } + } + else +#endif /* RE_ENABLE_I18N */ + build_upper_buffer (pstr); + } + else + { +#ifdef RE_ENABLE_I18N + if (dfa->mb_cur_max > 1) + build_wcs_buffer (pstr); + else +#endif /* RE_ENABLE_I18N */ + { + if (trans != NULL) + re_string_translate_buffer (pstr); + else + { + pstr->valid_len = pstr->bufs_len; + pstr->valid_raw_len = pstr->bufs_len; + } + } + } + + return REG_NOERROR; +} + +/* Helper functions for re_string_allocate, and re_string_construct. */ + +static reg_errcode_t +internal_function +re_string_realloc_buffers (re_string_t *pstr, Idx new_buf_len) +{ +#ifdef RE_ENABLE_I18N + if (pstr->mb_cur_max > 1) + { + wint_t *new_wcs; + + /* Avoid overflow. */ + size_t max_object_size = MAX (sizeof (wint_t), sizeof (Idx)); + if (BE (SIZE_MAX / max_object_size < new_buf_len, 0)) + return REG_ESPACE; + + new_wcs = re_realloc (pstr->wcs, wint_t, new_buf_len); + if (BE (new_wcs == NULL, 0)) + return REG_ESPACE; + pstr->wcs = new_wcs; + if (pstr->offsets != NULL) + { + Idx *new_offsets = re_realloc (pstr->offsets, Idx, new_buf_len); + if (BE (new_offsets == NULL, 0)) + return REG_ESPACE; + pstr->offsets = new_offsets; + } + } +#endif /* RE_ENABLE_I18N */ + if (pstr->mbs_allocated) + { + unsigned char *new_mbs = re_realloc (pstr->mbs, unsigned char, + new_buf_len); + if (BE (new_mbs == NULL, 0)) + return REG_ESPACE; + pstr->mbs = new_mbs; + } + pstr->bufs_len = new_buf_len; + return REG_NOERROR; +} + + +static void +internal_function +re_string_construct_common (const char *str, Idx len, re_string_t *pstr, + RE_TRANSLATE_TYPE trans, bool icase, + const re_dfa_t *dfa) +{ + pstr->raw_mbs = (const unsigned char *) str; + pstr->len = len; + pstr->raw_len = len; + pstr->trans = trans; + pstr->icase = icase; + pstr->mbs_allocated = (trans != NULL || icase); + pstr->mb_cur_max = dfa->mb_cur_max; + pstr->is_utf8 = dfa->is_utf8; + pstr->map_notascii = dfa->map_notascii; + pstr->stop = pstr->len; + pstr->raw_stop = pstr->stop; +} + +#ifdef RE_ENABLE_I18N + +/* Build wide character buffer PSTR->WCS. + If the byte sequence of the string are: + (0), (1), (0), (1), + Then wide character buffer will be: + , WEOF , , WEOF , + We use WEOF for padding, they indicate that the position isn't + a first byte of a multibyte character. + + Note that this function assumes PSTR->VALID_LEN elements are already + built and starts from PSTR->VALID_LEN. */ + +static void +internal_function +build_wcs_buffer (re_string_t *pstr) +{ +#ifdef _LIBC + unsigned char buf[MB_LEN_MAX]; + assert (MB_LEN_MAX >= pstr->mb_cur_max); +#else + unsigned char buf[64]; +#endif + mbstate_t prev_st; + Idx byte_idx, end_idx, remain_len; + size_t mbclen; + + /* Build the buffers from pstr->valid_len to either pstr->len or + pstr->bufs_len. */ + end_idx = (pstr->bufs_len > pstr->len) ? pstr->len : pstr->bufs_len; + for (byte_idx = pstr->valid_len; byte_idx < end_idx;) + { + wchar_t wc; + const char *p; + + remain_len = end_idx - byte_idx; + prev_st = pstr->cur_state; + /* Apply the translation if we need. */ + if (BE (pstr->trans != NULL, 0)) + { + int i, ch; + + for (i = 0; i < pstr->mb_cur_max && i < remain_len; ++i) + { + ch = pstr->raw_mbs [pstr->raw_mbs_idx + byte_idx + i]; + buf[i] = pstr->mbs[byte_idx + i] = pstr->trans[ch]; + } + p = (const char *) buf; + } + else + p = (const char *) pstr->raw_mbs + pstr->raw_mbs_idx + byte_idx; + mbclen = mbrtowc (&wc, p, remain_len, &pstr->cur_state); + if (BE (mbclen == (size_t) -2, 0)) + { + /* The buffer doesn't have enough space, finish to build. */ + pstr->cur_state = prev_st; + break; + } + else if (BE (mbclen == (size_t) -1 || mbclen == 0, 0)) + { + /* We treat these cases as a singlebyte character. */ + mbclen = 1; + wc = (wchar_t) pstr->raw_mbs[pstr->raw_mbs_idx + byte_idx]; + if (BE (pstr->trans != NULL, 0)) + wc = pstr->trans[wc]; + pstr->cur_state = prev_st; + } + + /* Write wide character and padding. */ + pstr->wcs[byte_idx++] = wc; + /* Write paddings. */ + for (remain_len = byte_idx + mbclen - 1; byte_idx < remain_len ;) + pstr->wcs[byte_idx++] = WEOF; + } + pstr->valid_len = byte_idx; + pstr->valid_raw_len = byte_idx; +} + +/* Build wide character buffer PSTR->WCS like build_wcs_buffer, + but for REG_ICASE. */ + +static reg_errcode_t +internal_function +build_wcs_upper_buffer (re_string_t *pstr) +{ + mbstate_t prev_st; + Idx src_idx, byte_idx, end_idx, remain_len; + size_t mbclen; +#ifdef _LIBC + char buf[MB_LEN_MAX]; + assert (MB_LEN_MAX >= pstr->mb_cur_max); +#else + char buf[64]; +#endif + + byte_idx = pstr->valid_len; + end_idx = (pstr->bufs_len > pstr->len) ? pstr->len : pstr->bufs_len; + + /* The following optimization assumes that ASCII characters can be + mapped to wide characters with a simple cast. */ + if (! pstr->map_notascii && pstr->trans == NULL && !pstr->offsets_needed) + { + while (byte_idx < end_idx) + { + wchar_t wc; + + if (isascii (pstr->raw_mbs[pstr->raw_mbs_idx + byte_idx]) + && mbsinit (&pstr->cur_state)) + { + /* In case of a singlebyte character. */ + pstr->mbs[byte_idx] + = toupper (pstr->raw_mbs[pstr->raw_mbs_idx + byte_idx]); + /* The next step uses the assumption that wchar_t is encoded + ASCII-safe: all ASCII values can be converted like this. */ + pstr->wcs[byte_idx] = (wchar_t) pstr->mbs[byte_idx]; + ++byte_idx; + continue; + } + + remain_len = end_idx - byte_idx; + prev_st = pstr->cur_state; + mbclen = mbrtowc (&wc, + ((const char *) pstr->raw_mbs + pstr->raw_mbs_idx + + byte_idx), remain_len, &pstr->cur_state); + if (BE (mbclen < (size_t) -2, 1)) + { + wchar_t wcu = wc; + if (iswlower (wc)) + { + size_t mbcdlen; + + wcu = towupper (wc); + mbcdlen = wcrtomb (buf, wcu, &prev_st); + if (BE (mbclen == mbcdlen, 1)) + memcpy (pstr->mbs + byte_idx, buf, mbclen); + else + { + src_idx = byte_idx; + goto offsets_needed; + } + } + else + memcpy (pstr->mbs + byte_idx, + pstr->raw_mbs + pstr->raw_mbs_idx + byte_idx, mbclen); + pstr->wcs[byte_idx++] = wcu; + /* Write paddings. */ + for (remain_len = byte_idx + mbclen - 1; byte_idx < remain_len ;) + pstr->wcs[byte_idx++] = WEOF; + } + else if (mbclen == (size_t) -1 || mbclen == 0) + { + /* It is an invalid character or '\0'. Just use the byte. */ + int ch = pstr->raw_mbs[pstr->raw_mbs_idx + byte_idx]; + pstr->mbs[byte_idx] = ch; + /* And also cast it to wide char. */ + pstr->wcs[byte_idx++] = (wchar_t) ch; + if (BE (mbclen == (size_t) -1, 0)) + pstr->cur_state = prev_st; + } + else + { + /* The buffer doesn't have enough space, finish to build. */ + pstr->cur_state = prev_st; + break; + } + } + pstr->valid_len = byte_idx; + pstr->valid_raw_len = byte_idx; + return REG_NOERROR; + } + else + for (src_idx = pstr->valid_raw_len; byte_idx < end_idx;) + { + wchar_t wc; + const char *p; + offsets_needed: + remain_len = end_idx - byte_idx; + prev_st = pstr->cur_state; + if (BE (pstr->trans != NULL, 0)) + { + int i, ch; + + for (i = 0; i < pstr->mb_cur_max && i < remain_len; ++i) + { + ch = pstr->raw_mbs [pstr->raw_mbs_idx + src_idx + i]; + buf[i] = pstr->trans[ch]; + } + p = (const char *) buf; + } + else + p = (const char *) pstr->raw_mbs + pstr->raw_mbs_idx + src_idx; + mbclen = mbrtowc (&wc, p, remain_len, &pstr->cur_state); + if (BE (mbclen < (size_t) -2, 1)) + { + wchar_t wcu = wc; + if (iswlower (wc)) + { + size_t mbcdlen; + + wcu = towupper (wc); + mbcdlen = wcrtomb ((char *) buf, wcu, &prev_st); + if (BE (mbclen == mbcdlen, 1)) + memcpy (pstr->mbs + byte_idx, buf, mbclen); + else if (mbcdlen != (size_t) -1) + { + size_t i; + + if (byte_idx + mbcdlen > pstr->bufs_len) + { + pstr->cur_state = prev_st; + break; + } + + if (pstr->offsets == NULL) + { + pstr->offsets = re_malloc (Idx, pstr->bufs_len); + + if (pstr->offsets == NULL) + return REG_ESPACE; + } + if (!pstr->offsets_needed) + { + for (i = 0; i < (size_t) byte_idx; ++i) + pstr->offsets[i] = i; + pstr->offsets_needed = 1; + } + + memcpy (pstr->mbs + byte_idx, buf, mbcdlen); + pstr->wcs[byte_idx] = wcu; + pstr->offsets[byte_idx] = src_idx; + for (i = 1; i < mbcdlen; ++i) + { + pstr->offsets[byte_idx + i] + = src_idx + (i < mbclen ? i : mbclen - 1); + pstr->wcs[byte_idx + i] = WEOF; + } + pstr->len += mbcdlen - mbclen; + if (pstr->raw_stop > src_idx) + pstr->stop += mbcdlen - mbclen; + end_idx = (pstr->bufs_len > pstr->len) + ? pstr->len : pstr->bufs_len; + byte_idx += mbcdlen; + src_idx += mbclen; + continue; + } + else + memcpy (pstr->mbs + byte_idx, p, mbclen); + } + else + memcpy (pstr->mbs + byte_idx, p, mbclen); + + if (BE (pstr->offsets_needed != 0, 0)) + { + size_t i; + for (i = 0; i < mbclen; ++i) + pstr->offsets[byte_idx + i] = src_idx + i; + } + src_idx += mbclen; + + pstr->wcs[byte_idx++] = wcu; + /* Write paddings. */ + for (remain_len = byte_idx + mbclen - 1; byte_idx < remain_len ;) + pstr->wcs[byte_idx++] = WEOF; + } + else if (mbclen == (size_t) -1 || mbclen == 0) + { + /* It is an invalid character or '\0'. Just use the byte. */ + int ch = pstr->raw_mbs[pstr->raw_mbs_idx + src_idx]; + + if (BE (pstr->trans != NULL, 0)) + ch = pstr->trans [ch]; + pstr->mbs[byte_idx] = ch; + + if (BE (pstr->offsets_needed != 0, 0)) + pstr->offsets[byte_idx] = src_idx; + ++src_idx; + + /* And also cast it to wide char. */ + pstr->wcs[byte_idx++] = (wchar_t) ch; + if (BE (mbclen == (size_t) -1, 0)) + pstr->cur_state = prev_st; + } + else + { + /* The buffer doesn't have enough space, finish to build. */ + pstr->cur_state = prev_st; + break; + } + } + pstr->valid_len = byte_idx; + pstr->valid_raw_len = src_idx; + return REG_NOERROR; +} + +/* Skip characters until the index becomes greater than NEW_RAW_IDX. + Return the index. */ + +static Idx +internal_function +re_string_skip_chars (re_string_t *pstr, Idx new_raw_idx, wint_t *last_wc) +{ + mbstate_t prev_st; + Idx rawbuf_idx; + size_t mbclen; + wint_t wc = WEOF; + + /* Skip the characters which are not necessary to check. */ + for (rawbuf_idx = pstr->raw_mbs_idx + pstr->valid_raw_len; + rawbuf_idx < new_raw_idx;) + { + wchar_t wc2; + Idx remain_len; + remain_len = pstr->len - rawbuf_idx; + prev_st = pstr->cur_state; + mbclen = mbrtowc (&wc2, (const char *) pstr->raw_mbs + rawbuf_idx, + remain_len, &pstr->cur_state); + if (BE (mbclen == (size_t) -2 || mbclen == (size_t) -1 || mbclen == 0, 0)) + { + /* We treat these cases as a single byte character. */ + if (mbclen == 0 || remain_len == 0) + wc = L'\0'; + else + wc = *(unsigned char *) (pstr->raw_mbs + rawbuf_idx); + mbclen = 1; + pstr->cur_state = prev_st; + } + else + wc = wc2; + /* Then proceed the next character. */ + rawbuf_idx += mbclen; + } + *last_wc = wc; + return rawbuf_idx; +} +#endif /* RE_ENABLE_I18N */ + +/* Build the buffer PSTR->MBS, and apply the translation if we need. + This function is used in case of REG_ICASE. */ + +static void +internal_function +build_upper_buffer (re_string_t *pstr) +{ + Idx char_idx, end_idx; + end_idx = (pstr->bufs_len > pstr->len) ? pstr->len : pstr->bufs_len; + + for (char_idx = pstr->valid_len; char_idx < end_idx; ++char_idx) + { + int ch = pstr->raw_mbs[pstr->raw_mbs_idx + char_idx]; + if (BE (pstr->trans != NULL, 0)) + ch = pstr->trans[ch]; + if (islower (ch)) + pstr->mbs[char_idx] = toupper (ch); + else + pstr->mbs[char_idx] = ch; + } + pstr->valid_len = char_idx; + pstr->valid_raw_len = char_idx; +} + +/* Apply TRANS to the buffer in PSTR. */ + +static void +internal_function +re_string_translate_buffer (re_string_t *pstr) +{ + Idx buf_idx, end_idx; + end_idx = (pstr->bufs_len > pstr->len) ? pstr->len : pstr->bufs_len; + + for (buf_idx = pstr->valid_len; buf_idx < end_idx; ++buf_idx) + { + int ch = pstr->raw_mbs[pstr->raw_mbs_idx + buf_idx]; + pstr->mbs[buf_idx] = pstr->trans[ch]; + } + + pstr->valid_len = buf_idx; + pstr->valid_raw_len = buf_idx; +} + +/* This function re-construct the buffers. + Concretely, convert to wide character in case of pstr->mb_cur_max > 1, + convert to upper case in case of REG_ICASE, apply translation. */ + +static reg_errcode_t +internal_function +re_string_reconstruct (re_string_t *pstr, Idx idx, int eflags) +{ + Idx offset; + + if (BE (pstr->raw_mbs_idx <= idx, 0)) + offset = idx - pstr->raw_mbs_idx; + else + { + /* Reset buffer. */ +#ifdef RE_ENABLE_I18N + if (pstr->mb_cur_max > 1) + memset (&pstr->cur_state, '\0', sizeof (mbstate_t)); +#endif /* RE_ENABLE_I18N */ + pstr->len = pstr->raw_len; + pstr->stop = pstr->raw_stop; + pstr->valid_len = 0; + pstr->raw_mbs_idx = 0; + pstr->valid_raw_len = 0; + pstr->offsets_needed = 0; + pstr->tip_context = ((eflags & REG_NOTBOL) ? CONTEXT_BEGBUF + : CONTEXT_NEWLINE | CONTEXT_BEGBUF); + if (!pstr->mbs_allocated) + pstr->mbs = (unsigned char *) pstr->raw_mbs; + offset = idx; + } + + if (BE (offset != 0, 1)) + { + /* Should the already checked characters be kept? */ + if (BE (offset < pstr->valid_raw_len, 1)) + { + /* Yes, move them to the front of the buffer. */ +#ifdef RE_ENABLE_I18N + if (BE (pstr->offsets_needed, 0)) + { + Idx low = 0, high = pstr->valid_len, mid; + do + { + mid = (high + low) / 2; + if (pstr->offsets[mid] > offset) + high = mid; + else if (pstr->offsets[mid] < offset) + low = mid + 1; + else + break; + } + while (low < high); + if (pstr->offsets[mid] < offset) + ++mid; + pstr->tip_context = re_string_context_at (pstr, mid - 1, + eflags); + /* This can be quite complicated, so handle specially + only the common and easy case where the character with + different length representation of lower and upper + case is present at or after offset. */ + if (pstr->valid_len > offset + && mid == offset && pstr->offsets[mid] == offset) + { + memmove (pstr->wcs, pstr->wcs + offset, + (pstr->valid_len - offset) * sizeof (wint_t)); + memmove (pstr->mbs, pstr->mbs + offset, pstr->valid_len - offset); + pstr->valid_len -= offset; + pstr->valid_raw_len -= offset; + for (low = 0; low < pstr->valid_len; low++) + pstr->offsets[low] = pstr->offsets[low + offset] - offset; + } + else + { + /* Otherwise, just find out how long the partial multibyte + character at offset is and fill it with WEOF/255. */ + pstr->len = pstr->raw_len - idx + offset; + pstr->stop = pstr->raw_stop - idx + offset; + pstr->offsets_needed = 0; + while (mid > 0 && pstr->offsets[mid - 1] == offset) + --mid; + while (mid < pstr->valid_len) + if (pstr->wcs[mid] != WEOF) + break; + else + ++mid; + if (mid == pstr->valid_len) + pstr->valid_len = 0; + else + { + pstr->valid_len = pstr->offsets[mid] - offset; + if (pstr->valid_len) + { + for (low = 0; low < pstr->valid_len; ++low) + pstr->wcs[low] = WEOF; + memset (pstr->mbs, 255, pstr->valid_len); + } + } + pstr->valid_raw_len = pstr->valid_len; + } + } + else +#endif + { + pstr->tip_context = re_string_context_at (pstr, offset - 1, + eflags); +#ifdef RE_ENABLE_I18N + if (pstr->mb_cur_max > 1) + memmove (pstr->wcs, pstr->wcs + offset, + (pstr->valid_len - offset) * sizeof (wint_t)); +#endif /* RE_ENABLE_I18N */ + if (BE (pstr->mbs_allocated, 0)) + memmove (pstr->mbs, pstr->mbs + offset, + pstr->valid_len - offset); + pstr->valid_len -= offset; + pstr->valid_raw_len -= offset; +#if DEBUG + assert (pstr->valid_len > 0); +#endif + } + } + else + { + /* No, skip all characters until IDX. */ + Idx prev_valid_len = pstr->valid_len; + +#ifdef RE_ENABLE_I18N + if (BE (pstr->offsets_needed, 0)) + { + pstr->len = pstr->raw_len - idx + offset; + pstr->stop = pstr->raw_stop - idx + offset; + pstr->offsets_needed = 0; + } +#endif + pstr->valid_len = 0; +#ifdef RE_ENABLE_I18N + if (pstr->mb_cur_max > 1) + { + Idx wcs_idx; + wint_t wc = WEOF; + + if (pstr->is_utf8) + { + const unsigned char *raw, *p, *end; + + /* Special case UTF-8. Multi-byte chars start with any + byte other than 0x80 - 0xbf. */ + raw = pstr->raw_mbs + pstr->raw_mbs_idx; + end = raw + (offset - pstr->mb_cur_max); + if (end < pstr->raw_mbs) + end = pstr->raw_mbs; + p = raw + offset - 1; +#ifdef _LIBC + /* We know the wchar_t encoding is UCS4, so for the simple + case, ASCII characters, skip the conversion step. */ + if (isascii (*p) && BE (pstr->trans == NULL, 1)) + { + memset (&pstr->cur_state, '\0', sizeof (mbstate_t)); + /* pstr->valid_len = 0; */ + wc = (wchar_t) *p; + } + else +#endif + for (; p >= end; --p) + if ((*p & 0xc0) != 0x80) + { + mbstate_t cur_state; + wchar_t wc2; + Idx mlen = raw + pstr->len - p; + unsigned char buf[6]; + size_t mbclen; + + if (BE (pstr->trans != NULL, 0)) + { + int i = mlen < 6 ? mlen : 6; + while (--i >= 0) + buf[i] = pstr->trans[p[i]]; + } + /* XXX Don't use mbrtowc, we know which conversion + to use (UTF-8 -> UCS4). */ + memset (&cur_state, 0, sizeof (cur_state)); + mbclen = mbrtowc (&wc2, (const char *) p, mlen, + &cur_state); + if (raw + offset - p <= mbclen + && mbclen < (size_t) -2) + { + memset (&pstr->cur_state, '\0', + sizeof (mbstate_t)); + pstr->valid_len = mbclen - (raw + offset - p); + wc = wc2; + } + break; + } + } + + if (wc == WEOF) + pstr->valid_len = re_string_skip_chars (pstr, idx, &wc) - idx; + if (wc == WEOF) + pstr->tip_context + = re_string_context_at (pstr, prev_valid_len - 1, eflags); + else + pstr->tip_context = ((BE (pstr->word_ops_used != 0, 0) + && IS_WIDE_WORD_CHAR (wc)) + ? CONTEXT_WORD + : ((IS_WIDE_NEWLINE (wc) + && pstr->newline_anchor) + ? CONTEXT_NEWLINE : 0)); + if (BE (pstr->valid_len, 0)) + { + for (wcs_idx = 0; wcs_idx < pstr->valid_len; ++wcs_idx) + pstr->wcs[wcs_idx] = WEOF; + if (pstr->mbs_allocated) + memset (pstr->mbs, 255, pstr->valid_len); + } + pstr->valid_raw_len = pstr->valid_len; + } + else +#endif /* RE_ENABLE_I18N */ + { + int c = pstr->raw_mbs[pstr->raw_mbs_idx + offset - 1]; + pstr->valid_raw_len = 0; + if (pstr->trans) + c = pstr->trans[c]; + pstr->tip_context = (bitset_contain (pstr->word_char, c) + ? CONTEXT_WORD + : ((IS_NEWLINE (c) && pstr->newline_anchor) + ? CONTEXT_NEWLINE : 0)); + } + } + if (!BE (pstr->mbs_allocated, 0)) + pstr->mbs += offset; + } + pstr->raw_mbs_idx = idx; + pstr->len -= offset; + pstr->stop -= offset; + + /* Then build the buffers. */ +#ifdef RE_ENABLE_I18N + if (pstr->mb_cur_max > 1) + { + if (pstr->icase) + { + reg_errcode_t ret = build_wcs_upper_buffer (pstr); + if (BE (ret != REG_NOERROR, 0)) + return ret; + } + else + build_wcs_buffer (pstr); + } + else +#endif /* RE_ENABLE_I18N */ + if (BE (pstr->mbs_allocated, 0)) + { + if (pstr->icase) + build_upper_buffer (pstr); + else if (pstr->trans != NULL) + re_string_translate_buffer (pstr); + } + else + pstr->valid_len = pstr->len; + + pstr->cur_idx = 0; + return REG_NOERROR; +} + +static unsigned char +internal_function __attribute ((pure)) +re_string_peek_byte_case (const re_string_t *pstr, Idx idx) +{ + int ch; + Idx off; + + /* Handle the common (easiest) cases first. */ + if (BE (!pstr->mbs_allocated, 1)) + return re_string_peek_byte (pstr, idx); + +#ifdef RE_ENABLE_I18N + if (pstr->mb_cur_max > 1 + && ! re_string_is_single_byte_char (pstr, pstr->cur_idx + idx)) + return re_string_peek_byte (pstr, idx); +#endif + + off = pstr->cur_idx + idx; +#ifdef RE_ENABLE_I18N + if (pstr->offsets_needed) + off = pstr->offsets[off]; +#endif + + ch = pstr->raw_mbs[pstr->raw_mbs_idx + off]; + +#ifdef RE_ENABLE_I18N + /* Ensure that e.g. for tr_TR.UTF-8 BACKSLASH DOTLESS SMALL LETTER I + this function returns CAPITAL LETTER I instead of first byte of + DOTLESS SMALL LETTER I. The latter would confuse the parser, + since peek_byte_case doesn't advance cur_idx in any way. */ + if (pstr->offsets_needed && !isascii (ch)) + return re_string_peek_byte (pstr, idx); +#endif + + return ch; +} + +static unsigned char +internal_function __attribute ((pure)) +re_string_fetch_byte_case (re_string_t *pstr) +{ + if (BE (!pstr->mbs_allocated, 1)) + return re_string_fetch_byte (pstr); + +#ifdef RE_ENABLE_I18N + if (pstr->offsets_needed) + { + Idx off; + int ch; + + /* For tr_TR.UTF-8 [[:islower:]] there is + [[: CAPITAL LETTER I WITH DOT lower:]] in mbs. Skip + in that case the whole multi-byte character and return + the original letter. On the other side, with + [[: DOTLESS SMALL LETTER I return [[:I, as doing + anything else would complicate things too much. */ + + if (!re_string_first_byte (pstr, pstr->cur_idx)) + return re_string_fetch_byte (pstr); + + off = pstr->offsets[pstr->cur_idx]; + ch = pstr->raw_mbs[pstr->raw_mbs_idx + off]; + + if (! isascii (ch)) + return re_string_fetch_byte (pstr); + + re_string_skip_bytes (pstr, + re_string_char_size_at (pstr, pstr->cur_idx)); + return ch; + } +#endif + + return pstr->raw_mbs[pstr->raw_mbs_idx + pstr->cur_idx++]; +} + +static void +internal_function +re_string_destruct (re_string_t *pstr) +{ +#ifdef RE_ENABLE_I18N + re_free (pstr->wcs); + re_free (pstr->offsets); +#endif /* RE_ENABLE_I18N */ + if (pstr->mbs_allocated) + re_free (pstr->mbs); +} + +/* Return the context at IDX in INPUT. */ + +static unsigned int +internal_function +re_string_context_at (const re_string_t *input, Idx idx, int eflags) +{ + int c; + if (BE (! REG_VALID_INDEX (idx), 0)) + /* In this case, we use the value stored in input->tip_context, + since we can't know the character in input->mbs[-1] here. */ + return input->tip_context; + if (BE (idx == input->len, 0)) + return ((eflags & REG_NOTEOL) ? CONTEXT_ENDBUF + : CONTEXT_NEWLINE | CONTEXT_ENDBUF); +#ifdef RE_ENABLE_I18N + if (input->mb_cur_max > 1) + { + wint_t wc; + Idx wc_idx = idx; + while(input->wcs[wc_idx] == WEOF) + { +#ifdef DEBUG + /* It must not happen. */ + assert (REG_VALID_INDEX (wc_idx)); +#endif + --wc_idx; + if (! REG_VALID_INDEX (wc_idx)) + return input->tip_context; + } + wc = input->wcs[wc_idx]; + if (BE (input->word_ops_used != 0, 0) && IS_WIDE_WORD_CHAR (wc)) + return CONTEXT_WORD; + return (IS_WIDE_NEWLINE (wc) && input->newline_anchor + ? CONTEXT_NEWLINE : 0); + } + else +#endif + { + c = re_string_byte_at (input, idx); + if (bitset_contain (input->word_char, c)) + return CONTEXT_WORD; + return IS_NEWLINE (c) && input->newline_anchor ? CONTEXT_NEWLINE : 0; + } +} + +/* Functions for set operation. */ + +static reg_errcode_t +internal_function +re_node_set_alloc (re_node_set *set, Idx size) +{ + set->alloc = size; + set->nelem = 0; + set->elems = re_malloc (Idx, size); + if (BE (set->elems == NULL, 0)) + return REG_ESPACE; + return REG_NOERROR; +} + +static reg_errcode_t +internal_function +re_node_set_init_1 (re_node_set *set, Idx elem) +{ + set->alloc = 1; + set->nelem = 1; + set->elems = re_malloc (Idx, 1); + if (BE (set->elems == NULL, 0)) + { + set->alloc = set->nelem = 0; + return REG_ESPACE; + } + set->elems[0] = elem; + return REG_NOERROR; +} + +static reg_errcode_t +internal_function +re_node_set_init_2 (re_node_set *set, Idx elem1, Idx elem2) +{ + set->alloc = 2; + set->elems = re_malloc (Idx, 2); + if (BE (set->elems == NULL, 0)) + return REG_ESPACE; + if (elem1 == elem2) + { + set->nelem = 1; + set->elems[0] = elem1; + } + else + { + set->nelem = 2; + if (elem1 < elem2) + { + set->elems[0] = elem1; + set->elems[1] = elem2; + } + else + { + set->elems[0] = elem2; + set->elems[1] = elem1; + } + } + return REG_NOERROR; +} + +static reg_errcode_t +internal_function +re_node_set_init_copy (re_node_set *dest, const re_node_set *src) +{ + dest->nelem = src->nelem; + if (src->nelem > 0) + { + dest->alloc = dest->nelem; + dest->elems = re_malloc (Idx, dest->alloc); + if (BE (dest->elems == NULL, 0)) + { + dest->alloc = dest->nelem = 0; + return REG_ESPACE; + } + memcpy (dest->elems, src->elems, src->nelem * sizeof (Idx)); + } + else + re_node_set_init_empty (dest); + return REG_NOERROR; +} + +/* Calculate the intersection of the sets SRC1 and SRC2. And merge it to + DEST. Return value indicate the error code or REG_NOERROR if succeeded. + Note: We assume dest->elems is NULL, when dest->alloc is 0. */ + +static reg_errcode_t +internal_function +re_node_set_add_intersect (re_node_set *dest, const re_node_set *src1, + const re_node_set *src2) +{ + Idx i1, i2, is, id, delta, sbase; + if (src1->nelem == 0 || src2->nelem == 0) + return REG_NOERROR; + + /* We need dest->nelem + 2 * elems_in_intersection; this is a + conservative estimate. */ + if (src1->nelem + src2->nelem + dest->nelem > dest->alloc) + { + Idx new_alloc = src1->nelem + src2->nelem + dest->alloc; + Idx *new_elems = re_realloc (dest->elems, Idx, new_alloc); + if (BE (new_elems == NULL, 0)) + return REG_ESPACE; + dest->elems = new_elems; + dest->alloc = new_alloc; + } + + /* Find the items in the intersection of SRC1 and SRC2, and copy + into the top of DEST those that are not already in DEST itself. */ + sbase = dest->nelem + src1->nelem + src2->nelem; + i1 = src1->nelem - 1; + i2 = src2->nelem - 1; + id = dest->nelem - 1; + for (;;) + { + if (src1->elems[i1] == src2->elems[i2]) + { + /* Try to find the item in DEST. Maybe we could binary search? */ + while (REG_VALID_INDEX (id) && dest->elems[id] > src1->elems[i1]) + --id; + + if (! REG_VALID_INDEX (id) || dest->elems[id] != src1->elems[i1]) + dest->elems[--sbase] = src1->elems[i1]; + + if (! REG_VALID_INDEX (--i1) || ! REG_VALID_INDEX (--i2)) + break; + } + + /* Lower the highest of the two items. */ + else if (src1->elems[i1] < src2->elems[i2]) + { + if (! REG_VALID_INDEX (--i2)) + break; + } + else + { + if (! REG_VALID_INDEX (--i1)) + break; + } + } + + id = dest->nelem - 1; + is = dest->nelem + src1->nelem + src2->nelem - 1; + delta = is - sbase + 1; + + /* Now copy. When DELTA becomes zero, the remaining + DEST elements are already in place; this is more or + less the same loop that is in re_node_set_merge. */ + dest->nelem += delta; + if (delta > 0 && REG_VALID_INDEX (id)) + for (;;) + { + if (dest->elems[is] > dest->elems[id]) + { + /* Copy from the top. */ + dest->elems[id + delta--] = dest->elems[is--]; + if (delta == 0) + break; + } + else + { + /* Slide from the bottom. */ + dest->elems[id + delta] = dest->elems[id]; + if (! REG_VALID_INDEX (--id)) + break; + } + } + + /* Copy remaining SRC elements. */ + memcpy (dest->elems, dest->elems + sbase, delta * sizeof (Idx)); + + return REG_NOERROR; +} + +/* Calculate the union set of the sets SRC1 and SRC2. And store it to + DEST. Return value indicate the error code or REG_NOERROR if succeeded. */ + +static reg_errcode_t +internal_function +re_node_set_init_union (re_node_set *dest, const re_node_set *src1, + const re_node_set *src2) +{ + Idx i1, i2, id; + if (src1 != NULL && src1->nelem > 0 && src2 != NULL && src2->nelem > 0) + { + dest->alloc = src1->nelem + src2->nelem; + dest->elems = re_malloc (Idx, dest->alloc); + if (BE (dest->elems == NULL, 0)) + return REG_ESPACE; + } + else + { + if (src1 != NULL && src1->nelem > 0) + return re_node_set_init_copy (dest, src1); + else if (src2 != NULL && src2->nelem > 0) + return re_node_set_init_copy (dest, src2); + else + re_node_set_init_empty (dest); + return REG_NOERROR; + } + for (i1 = i2 = id = 0 ; i1 < src1->nelem && i2 < src2->nelem ;) + { + if (src1->elems[i1] > src2->elems[i2]) + { + dest->elems[id++] = src2->elems[i2++]; + continue; + } + if (src1->elems[i1] == src2->elems[i2]) + ++i2; + dest->elems[id++] = src1->elems[i1++]; + } + if (i1 < src1->nelem) + { + memcpy (dest->elems + id, src1->elems + i1, + (src1->nelem - i1) * sizeof (Idx)); + id += src1->nelem - i1; + } + else if (i2 < src2->nelem) + { + memcpy (dest->elems + id, src2->elems + i2, + (src2->nelem - i2) * sizeof (Idx)); + id += src2->nelem - i2; + } + dest->nelem = id; + return REG_NOERROR; +} + +/* Calculate the union set of the sets DEST and SRC. And store it to + DEST. Return value indicate the error code or REG_NOERROR if succeeded. */ + +static reg_errcode_t +internal_function +re_node_set_merge (re_node_set *dest, const re_node_set *src) +{ + Idx is, id, sbase, delta; + if (src == NULL || src->nelem == 0) + return REG_NOERROR; + if (dest->alloc < 2 * src->nelem + dest->nelem) + { + Idx new_alloc = 2 * (src->nelem + dest->alloc); + Idx *new_buffer = re_realloc (dest->elems, Idx, new_alloc); + if (BE (new_buffer == NULL, 0)) + return REG_ESPACE; + dest->elems = new_buffer; + dest->alloc = new_alloc; + } + + if (BE (dest->nelem == 0, 0)) + { + dest->nelem = src->nelem; + memcpy (dest->elems, src->elems, src->nelem * sizeof (Idx)); + return REG_NOERROR; + } + + /* Copy into the top of DEST the items of SRC that are not + found in DEST. Maybe we could binary search in DEST? */ + for (sbase = dest->nelem + 2 * src->nelem, + is = src->nelem - 1, id = dest->nelem - 1; + REG_VALID_INDEX (is) && REG_VALID_INDEX (id); ) + { + if (dest->elems[id] == src->elems[is]) + is--, id--; + else if (dest->elems[id] < src->elems[is]) + dest->elems[--sbase] = src->elems[is--]; + else /* if (dest->elems[id] > src->elems[is]) */ + --id; + } + + if (REG_VALID_INDEX (is)) + { + /* If DEST is exhausted, the remaining items of SRC must be unique. */ + sbase -= is + 1; + memcpy (dest->elems + sbase, src->elems, (is + 1) * sizeof (Idx)); + } + + id = dest->nelem - 1; + is = dest->nelem + 2 * src->nelem - 1; + delta = is - sbase + 1; + if (delta == 0) + return REG_NOERROR; + + /* Now copy. When DELTA becomes zero, the remaining + DEST elements are already in place. */ + dest->nelem += delta; + for (;;) + { + if (dest->elems[is] > dest->elems[id]) + { + /* Copy from the top. */ + dest->elems[id + delta--] = dest->elems[is--]; + if (delta == 0) + break; + } + else + { + /* Slide from the bottom. */ + dest->elems[id + delta] = dest->elems[id]; + if (! REG_VALID_INDEX (--id)) + { + /* Copy remaining SRC elements. */ + memcpy (dest->elems, dest->elems + sbase, + delta * sizeof (Idx)); + break; + } + } + } + + return REG_NOERROR; +} + +/* Insert the new element ELEM to the re_node_set* SET. + SET should not already have ELEM. + Return true if successful. */ + +static bool +internal_function +re_node_set_insert (re_node_set *set, Idx elem) +{ + Idx idx; + /* In case the set is empty. */ + if (set->alloc == 0) + return BE (re_node_set_init_1 (set, elem) == REG_NOERROR, 1); + + if (BE (set->nelem, 0) == 0) + { + /* We already guaranteed above that set->alloc != 0. */ + set->elems[0] = elem; + ++set->nelem; + return true; + } + + /* Realloc if we need. */ + if (set->alloc == set->nelem) + { + Idx *new_elems; + set->alloc = set->alloc * 2; + new_elems = re_realloc (set->elems, Idx, set->alloc); + if (BE (new_elems == NULL, 0)) + return false; + set->elems = new_elems; + } + + /* Move the elements which follows the new element. Test the + first element separately to skip a check in the inner loop. */ + if (elem < set->elems[0]) + { + idx = 0; + for (idx = set->nelem; idx > 0; idx--) + set->elems[idx] = set->elems[idx - 1]; + } + else + { + for (idx = set->nelem; set->elems[idx - 1] > elem; idx--) + set->elems[idx] = set->elems[idx - 1]; + } + + /* Insert the new element. */ + set->elems[idx] = elem; + ++set->nelem; + return true; +} + +/* Insert the new element ELEM to the re_node_set* SET. + SET should not already have any element greater than or equal to ELEM. + Return true if successful. */ + +static bool +internal_function +re_node_set_insert_last (re_node_set *set, Idx elem) +{ + /* Realloc if we need. */ + if (set->alloc == set->nelem) + { + Idx *new_elems; + set->alloc = (set->alloc + 1) * 2; + new_elems = re_realloc (set->elems, Idx, set->alloc); + if (BE (new_elems == NULL, 0)) + return false; + set->elems = new_elems; + } + + /* Insert the new element. */ + set->elems[set->nelem++] = elem; + return true; +} + +/* Compare two node sets SET1 and SET2. + Return true if SET1 and SET2 are equivalent. */ + +static bool +internal_function __attribute ((pure)) +re_node_set_compare (const re_node_set *set1, const re_node_set *set2) +{ + Idx i; + if (set1 == NULL || set2 == NULL || set1->nelem != set2->nelem) + return false; + for (i = set1->nelem ; REG_VALID_INDEX (--i) ; ) + if (set1->elems[i] != set2->elems[i]) + return false; + return true; +} + +/* Return (idx + 1) if SET contains the element ELEM, return 0 otherwise. */ + +static Idx +internal_function __attribute ((pure)) +re_node_set_contains (const re_node_set *set, Idx elem) +{ + __re_size_t idx, right, mid; + if (! REG_VALID_NONZERO_INDEX (set->nelem)) + return 0; + + /* Binary search the element. */ + idx = 0; + right = set->nelem - 1; + while (idx < right) + { + mid = (idx + right) / 2; + if (set->elems[mid] < elem) + idx = mid + 1; + else + right = mid; + } + return set->elems[idx] == elem ? idx + 1 : 0; +} + +static void +internal_function +re_node_set_remove_at (re_node_set *set, Idx idx) +{ + if (idx < 0 || idx >= set->nelem) + return; + --set->nelem; + for (; idx < set->nelem; idx++) + set->elems[idx] = set->elems[idx + 1]; +} + + +/* Add the token TOKEN to dfa->nodes, and return the index of the token. + Or return REG_MISSING if an error occurred. */ + +static Idx +internal_function +re_dfa_add_node (re_dfa_t *dfa, re_token_t token) +{ + if (BE (dfa->nodes_len >= dfa->nodes_alloc, 0)) + { + size_t new_nodes_alloc = dfa->nodes_alloc * 2; + Idx *new_nexts, *new_indices; + re_node_set *new_edests, *new_eclosures; + re_token_t *new_nodes; + size_t max_object_size = + MAX (sizeof (re_token_t), + MAX (sizeof (re_node_set), + sizeof (Idx))); + + /* Avoid overflows. */ + if (BE (SIZE_MAX / 2 / max_object_size < dfa->nodes_alloc, 0)) + return REG_MISSING; + + new_nodes = re_realloc (dfa->nodes, re_token_t, new_nodes_alloc); + if (BE (new_nodes == NULL, 0)) + return REG_MISSING; + dfa->nodes = new_nodes; + new_nexts = re_realloc (dfa->nexts, Idx, new_nodes_alloc); + new_indices = re_realloc (dfa->org_indices, Idx, new_nodes_alloc); + new_edests = re_realloc (dfa->edests, re_node_set, new_nodes_alloc); + new_eclosures = re_realloc (dfa->eclosures, re_node_set, new_nodes_alloc); + if (BE (new_nexts == NULL || new_indices == NULL + || new_edests == NULL || new_eclosures == NULL, 0)) + return REG_MISSING; + dfa->nexts = new_nexts; + dfa->org_indices = new_indices; + dfa->edests = new_edests; + dfa->eclosures = new_eclosures; + dfa->nodes_alloc = new_nodes_alloc; + } + dfa->nodes[dfa->nodes_len] = token; + dfa->nodes[dfa->nodes_len].constraint = 0; +#ifdef RE_ENABLE_I18N + { + int type = token.type; + dfa->nodes[dfa->nodes_len].accept_mb = + (type == OP_PERIOD && dfa->mb_cur_max > 1) || type == COMPLEX_BRACKET; + } +#endif + dfa->nexts[dfa->nodes_len] = REG_MISSING; + re_node_set_init_empty (dfa->edests + dfa->nodes_len); + re_node_set_init_empty (dfa->eclosures + dfa->nodes_len); + return dfa->nodes_len++; +} + +static inline re_hashval_t +internal_function +calc_state_hash (const re_node_set *nodes, unsigned int context) +{ + re_hashval_t hash = nodes->nelem + context; + Idx i; + for (i = 0 ; i < nodes->nelem ; i++) + hash += nodes->elems[i]; + return hash; +} + +/* Search for the state whose node_set is equivalent to NODES. + Return the pointer to the state, if we found it in the DFA. + Otherwise create the new one and return it. In case of an error + return NULL and set the error code in ERR. + Note: - We assume NULL as the invalid state, then it is possible that + return value is NULL and ERR is REG_NOERROR. + - We never return non-NULL value in case of any errors, it is for + optimization. */ + +static re_dfastate_t * +internal_function +re_acquire_state (reg_errcode_t *err, const re_dfa_t *dfa, + const re_node_set *nodes) +{ + re_hashval_t hash; + re_dfastate_t *new_state; + struct re_state_table_entry *spot; + Idx i; +#ifdef lint + /* Suppress bogus uninitialized-variable warnings. */ + *err = REG_NOERROR; +#endif + if (BE (nodes->nelem == 0, 0)) + { + *err = REG_NOERROR; + return NULL; + } + hash = calc_state_hash (nodes, 0); + spot = dfa->state_table + (hash & dfa->state_hash_mask); + + for (i = 0 ; i < spot->num ; i++) + { + re_dfastate_t *state = spot->array[i]; + if (hash != state->hash) + continue; + if (re_node_set_compare (&state->nodes, nodes)) + return state; + } + + /* There are no appropriate state in the dfa, create the new one. */ + new_state = create_ci_newstate (dfa, nodes, hash); + if (BE (new_state == NULL, 0)) + *err = REG_ESPACE; + + return new_state; +} + +/* Search for the state whose node_set is equivalent to NODES and + whose context is equivalent to CONTEXT. + Return the pointer to the state, if we found it in the DFA. + Otherwise create the new one and return it. In case of an error + return NULL and set the error code in ERR. + Note: - We assume NULL as the invalid state, then it is possible that + return value is NULL and ERR is REG_NOERROR. + - We never return non-NULL value in case of any errors, it is for + optimization. */ + +static re_dfastate_t * +internal_function +re_acquire_state_context (reg_errcode_t *err, const re_dfa_t *dfa, + const re_node_set *nodes, unsigned int context) +{ + re_hashval_t hash; + re_dfastate_t *new_state; + struct re_state_table_entry *spot; + Idx i; +#ifdef lint + /* Suppress bogus uninitialized-variable warnings. */ + *err = REG_NOERROR; +#endif + if (nodes->nelem == 0) + { + *err = REG_NOERROR; + return NULL; + } + hash = calc_state_hash (nodes, context); + spot = dfa->state_table + (hash & dfa->state_hash_mask); + + for (i = 0 ; i < spot->num ; i++) + { + re_dfastate_t *state = spot->array[i]; + if (state->hash == hash + && state->context == context + && re_node_set_compare (state->entrance_nodes, nodes)) + return state; + } + /* There are no appropriate state in `dfa', create the new one. */ + new_state = create_cd_newstate (dfa, nodes, context, hash); + if (BE (new_state == NULL, 0)) + *err = REG_ESPACE; + + return new_state; +} + +/* Finish initialization of the new state NEWSTATE, and using its hash value + HASH put in the appropriate bucket of DFA's state table. Return value + indicates the error code if failed. */ + +static reg_errcode_t +register_state (const re_dfa_t *dfa, re_dfastate_t *newstate, + re_hashval_t hash) +{ + struct re_state_table_entry *spot; + reg_errcode_t err; + Idx i; + + newstate->hash = hash; + err = re_node_set_alloc (&newstate->non_eps_nodes, newstate->nodes.nelem); + if (BE (err != REG_NOERROR, 0)) + return REG_ESPACE; + for (i = 0; i < newstate->nodes.nelem; i++) + { + Idx elem = newstate->nodes.elems[i]; + if (!IS_EPSILON_NODE (dfa->nodes[elem].type)) + if (BE (! re_node_set_insert_last (&newstate->non_eps_nodes, elem), 0)) + return REG_ESPACE; + } + + spot = dfa->state_table + (hash & dfa->state_hash_mask); + if (BE (spot->alloc <= spot->num, 0)) + { + Idx new_alloc = 2 * spot->num + 2; + re_dfastate_t **new_array = re_realloc (spot->array, re_dfastate_t *, + new_alloc); + if (BE (new_array == NULL, 0)) + return REG_ESPACE; + spot->array = new_array; + spot->alloc = new_alloc; + } + spot->array[spot->num++] = newstate; + return REG_NOERROR; +} + +static void +free_state (re_dfastate_t *state) +{ + re_node_set_free (&state->non_eps_nodes); + re_node_set_free (&state->inveclosure); + if (state->entrance_nodes != &state->nodes) + { + re_node_set_free (state->entrance_nodes); + re_free (state->entrance_nodes); + } + re_node_set_free (&state->nodes); + re_free (state->word_trtable); + re_free (state->trtable); + re_free (state); +} + +/* Create the new state which is independ of contexts. + Return the new state if succeeded, otherwise return NULL. */ + +static re_dfastate_t * +internal_function +create_ci_newstate (const re_dfa_t *dfa, const re_node_set *nodes, + re_hashval_t hash) +{ + Idx i; + reg_errcode_t err; + re_dfastate_t *newstate; + + newstate = (re_dfastate_t *) calloc (sizeof (re_dfastate_t), 1); + if (BE (newstate == NULL, 0)) + return NULL; + err = re_node_set_init_copy (&newstate->nodes, nodes); + if (BE (err != REG_NOERROR, 0)) + { + re_free (newstate); + return NULL; + } + + newstate->entrance_nodes = &newstate->nodes; + for (i = 0 ; i < nodes->nelem ; i++) + { + re_token_t *node = dfa->nodes + nodes->elems[i]; + re_token_type_t type = node->type; + if (type == CHARACTER && !node->constraint) + continue; +#ifdef RE_ENABLE_I18N + newstate->accept_mb |= node->accept_mb; +#endif /* RE_ENABLE_I18N */ + + /* If the state has the halt node, the state is a halt state. */ + if (type == END_OF_RE) + newstate->halt = 1; + else if (type == OP_BACK_REF) + newstate->has_backref = 1; + else if (type == ANCHOR || node->constraint) + newstate->has_constraint = 1; + } + err = register_state (dfa, newstate, hash); + if (BE (err != REG_NOERROR, 0)) + { + free_state (newstate); + newstate = NULL; + } + return newstate; +} + +/* Create the new state which is depend on the context CONTEXT. + Return the new state if succeeded, otherwise return NULL. */ + +static re_dfastate_t * +internal_function +create_cd_newstate (const re_dfa_t *dfa, const re_node_set *nodes, + unsigned int context, re_hashval_t hash) +{ + Idx i, nctx_nodes = 0; + reg_errcode_t err; + re_dfastate_t *newstate; + + newstate = (re_dfastate_t *) calloc (sizeof (re_dfastate_t), 1); + if (BE (newstate == NULL, 0)) + return NULL; + err = re_node_set_init_copy (&newstate->nodes, nodes); + if (BE (err != REG_NOERROR, 0)) + { + re_free (newstate); + return NULL; + } + + newstate->context = context; + newstate->entrance_nodes = &newstate->nodes; + + for (i = 0 ; i < nodes->nelem ; i++) + { + unsigned int constraint = 0; + re_token_t *node = dfa->nodes + nodes->elems[i]; + re_token_type_t type = node->type; + if (node->constraint) + constraint = node->constraint; + + if (type == CHARACTER && !constraint) + continue; +#ifdef RE_ENABLE_I18N + newstate->accept_mb |= node->accept_mb; +#endif /* RE_ENABLE_I18N */ + + /* If the state has the halt node, the state is a halt state. */ + if (type == END_OF_RE) + newstate->halt = 1; + else if (type == OP_BACK_REF) + newstate->has_backref = 1; + else if (type == ANCHOR) + constraint = node->opr.ctx_type; + + if (constraint) + { + if (newstate->entrance_nodes == &newstate->nodes) + { + newstate->entrance_nodes = re_malloc (re_node_set, 1); + if (BE (newstate->entrance_nodes == NULL, 0)) + { + free_state (newstate); + return NULL; + } + re_node_set_init_copy (newstate->entrance_nodes, nodes); + nctx_nodes = 0; + newstate->has_constraint = 1; + } + + if (NOT_SATISFY_PREV_CONSTRAINT (constraint,context)) + { + re_node_set_remove_at (&newstate->nodes, i - nctx_nodes); + ++nctx_nodes; + } + } + } + err = register_state (dfa, newstate, hash); + if (BE (err != REG_NOERROR, 0)) + { + free_state (newstate); + newstate = NULL; + } + return newstate; +} diff --git a/src/bin/findutils/gnulib/lib/regex_internal.h b/src/bin/findutils/gnulib/lib/regex_internal.h new file mode 100644 index 0000000000..f96291d00d --- /dev/null +++ b/src/bin/findutils/gnulib/lib/regex_internal.h @@ -0,0 +1,857 @@ +/* Extended regular expression matching and search library. + Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Isamu Hasegawa . + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _REGEX_INTERNAL_H +#define _REGEX_INTERNAL_H 1 + +#include +#include +#include +#include +#include +#include + +#ifdef _LIBC +# include +#else +# include "localcharset.h" +#endif +#if defined HAVE_LOCALE_H || defined _LIBC +# include +#endif + +#include +#include +#include +#if defined _LIBC +# include +#else +# define __libc_lock_init(NAME) do { } while (0) +# define __libc_lock_lock(NAME) do { } while (0) +# define __libc_lock_unlock(NAME) do { } while (0) +#endif + +/* In case that the system doesn't have isblank(). */ +#if !defined _LIBC && ! (defined isblank || (HAVE_ISBLANK && HAVE_DECL_ISBLANK)) +# define isblank(ch) ((ch) == ' ' || (ch) == '\t') +#endif + +#ifdef _LIBC +# ifndef _RE_DEFINE_LOCALE_FUNCTIONS +# define _RE_DEFINE_LOCALE_FUNCTIONS 1 +# include +# include +# include +# endif +#endif + +/* This is for other GNU distributions with internationalized messages. */ +#if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC +# include +# ifdef _LIBC +# undef gettext +# define gettext(msgid) \ + INTUSE(__dcgettext) (_libc_intl_domainname, msgid, LC_MESSAGES) +# endif +#else +# define gettext(msgid) (msgid) +#endif + +#ifndef gettext_noop +/* This define is so xgettext can find the internationalizable + strings. */ +# define gettext_noop(String) String +#endif + +/* For loser systems without the definition. */ +#ifndef SIZE_MAX +# define SIZE_MAX ((size_t) -1) +#endif + +#if (defined MB_CUR_MAX && HAVE_LOCALE_H && HAVE_WCTYPE_H && HAVE_ISWCTYPE && HAVE_WCRTOMB && HAVE_MBRTOWC && HAVE_WCSCOLL) || _LIBC +# define RE_ENABLE_I18N +#endif + +#if __GNUC__ >= 3 +# define BE(expr, val) __builtin_expect (expr, val) +#else +# define BE(expr, val) (expr) +# ifdef _LIBC +# define inline +# endif +#endif + +/* Number of ASCII characters. */ +#define ASCII_CHARS 0x80 + +/* Number of single byte characters. */ +#define SBC_MAX (UCHAR_MAX + 1) + +#define COLL_ELEM_LEN_MAX 8 + +/* The character which represents newline. */ +#define NEWLINE_CHAR '\n' +#define WIDE_NEWLINE_CHAR L'\n' + +/* Rename to standard API for using out of glibc. */ +#ifndef _LIBC +# define __wctype wctype +# define __iswctype iswctype +# define __btowc btowc +# define __wcrtomb wcrtomb +# define __regfree regfree +# define attribute_hidden +#endif /* not _LIBC */ + +#if __GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1) +# define __attribute(arg) __attribute__ (arg) +#else +# define __attribute(arg) +#endif + +typedef __re_idx_t Idx; + +/* Special return value for failure to match. */ +#define REG_MISSING ((Idx) -1) + +/* Special return value for internal error. */ +#define REG_ERROR ((Idx) -2) + +/* Test whether N is a valid index, and is not one of the above. */ +#ifdef _REGEX_LARGE_OFFSETS +# define REG_VALID_INDEX(n) ((Idx) (n) < REG_ERROR) +#else +# define REG_VALID_INDEX(n) (0 <= (n)) +#endif + +/* Test whether N is a valid nonzero index. */ +#ifdef _REGEX_LARGE_OFFSETS +# define REG_VALID_NONZERO_INDEX(n) ((Idx) ((n) - 1) < (Idx) (REG_ERROR - 1)) +#else +# define REG_VALID_NONZERO_INDEX(n) (0 < (n)) +#endif + +/* A hash value, suitable for computing hash tables. */ +typedef __re_size_t re_hashval_t; + +/* An integer used to represent a set of bits. It must be unsigned, + and must be at least as wide as unsigned int. */ +typedef unsigned long int bitset_word_t; +/* All bits set in a bitset_word_t. */ +#define BITSET_WORD_MAX ULONG_MAX + +/* Number of bits in a bitset_word_t. For portability to hosts with + padding bits, do not use '(sizeof (bitset_word_t) * CHAR_BIT)'; + instead, deduce it directly from BITSET_WORD_MAX. Avoid + greater-than-32-bit integers and unconditional shifts by more than + 31 bits, as they're not portable. */ +#if BITSET_WORD_MAX == 0xffffffff +# define BITSET_WORD_BITS 32 +#elif BITSET_WORD_MAX >> 31 >> 5 == 1 +# define BITSET_WORD_BITS 36 +#elif BITSET_WORD_MAX >> 31 >> 16 == 1 +# define BITSET_WORD_BITS 48 +#elif BITSET_WORD_MAX >> 31 >> 28 == 1 +# define BITSET_WORD_BITS 60 +#elif BITSET_WORD_MAX >> 31 >> 31 >> 1 == 1 +# define BITSET_WORD_BITS 64 +#elif BITSET_WORD_MAX >> 31 >> 31 >> 9 == 1 +# define BITSET_WORD_BITS 72 +#elif BITSET_WORD_MAX >> 31 >> 31 >> 31 >> 31 >> 3 == 1 +# define BITSET_WORD_BITS 128 +#elif BITSET_WORD_MAX >> 31 >> 31 >> 31 >> 31 >> 31 >> 31 >> 31 >> 31 >> 7 == 1 +# define BITSET_WORD_BITS 256 +#elif BITSET_WORD_MAX >> 31 >> 31 >> 31 >> 31 >> 31 >> 31 >> 31 >> 31 >> 7 > 1 +# define BITSET_WORD_BITS 257 /* any value > SBC_MAX will do here */ +# if BITSET_WORD_BITS <= SBC_MAX +# error "Invalid SBC_MAX" +# endif +#elif BITSET_WORD_MAX == (0xffffffff + 2) * 0xffffffff +/* Work around a bug in 64-bit PGC (before version 6.1-2), where the + preprocessor mishandles large unsigned values as if they were signed. */ +# define BITSET_WORD_BITS 64 +#else +# error "Add case for new bitset_word_t size" +#endif + +/* Number of bitset_word_t values in a bitset_t. */ +#define BITSET_WORDS ((SBC_MAX + BITSET_WORD_BITS - 1) / BITSET_WORD_BITS) + +typedef bitset_word_t bitset_t[BITSET_WORDS]; +typedef bitset_word_t *re_bitset_ptr_t; +typedef const bitset_word_t *re_const_bitset_ptr_t; + +#define PREV_WORD_CONSTRAINT 0x0001 +#define PREV_NOTWORD_CONSTRAINT 0x0002 +#define NEXT_WORD_CONSTRAINT 0x0004 +#define NEXT_NOTWORD_CONSTRAINT 0x0008 +#define PREV_NEWLINE_CONSTRAINT 0x0010 +#define NEXT_NEWLINE_CONSTRAINT 0x0020 +#define PREV_BEGBUF_CONSTRAINT 0x0040 +#define NEXT_ENDBUF_CONSTRAINT 0x0080 +#define WORD_DELIM_CONSTRAINT 0x0100 +#define NOT_WORD_DELIM_CONSTRAINT 0x0200 + +typedef enum +{ + INSIDE_WORD = PREV_WORD_CONSTRAINT | NEXT_WORD_CONSTRAINT, + WORD_FIRST = PREV_NOTWORD_CONSTRAINT | NEXT_WORD_CONSTRAINT, + WORD_LAST = PREV_WORD_CONSTRAINT | NEXT_NOTWORD_CONSTRAINT, + INSIDE_NOTWORD = PREV_NOTWORD_CONSTRAINT | NEXT_NOTWORD_CONSTRAINT, + LINE_FIRST = PREV_NEWLINE_CONSTRAINT, + LINE_LAST = NEXT_NEWLINE_CONSTRAINT, + BUF_FIRST = PREV_BEGBUF_CONSTRAINT, + BUF_LAST = NEXT_ENDBUF_CONSTRAINT, + WORD_DELIM = WORD_DELIM_CONSTRAINT, + NOT_WORD_DELIM = NOT_WORD_DELIM_CONSTRAINT +} re_context_type; + +typedef struct +{ + Idx alloc; + Idx nelem; + Idx *elems; +} re_node_set; + +typedef enum +{ + NON_TYPE = 0, + + /* Node type, These are used by token, node, tree. */ + CHARACTER = 1, + END_OF_RE = 2, + SIMPLE_BRACKET = 3, + OP_BACK_REF = 4, + OP_PERIOD = 5, +#ifdef RE_ENABLE_I18N + COMPLEX_BRACKET = 6, + OP_UTF8_PERIOD = 7, +#endif /* RE_ENABLE_I18N */ + + /* We define EPSILON_BIT as a macro so that OP_OPEN_SUBEXP is used + when the debugger shows values of this enum type. */ +#define EPSILON_BIT 8 + OP_OPEN_SUBEXP = EPSILON_BIT | 0, + OP_CLOSE_SUBEXP = EPSILON_BIT | 1, + OP_ALT = EPSILON_BIT | 2, + OP_DUP_ASTERISK = EPSILON_BIT | 3, + ANCHOR = EPSILON_BIT | 4, + + /* Tree type, these are used only by tree. */ + CONCAT = 16, + SUBEXP = 17, + + /* Token type, these are used only by token. */ + OP_DUP_PLUS = 18, + OP_DUP_QUESTION, + OP_OPEN_BRACKET, + OP_CLOSE_BRACKET, + OP_CHARSET_RANGE, + OP_OPEN_DUP_NUM, + OP_CLOSE_DUP_NUM, + OP_NON_MATCH_LIST, + OP_OPEN_COLL_ELEM, + OP_CLOSE_COLL_ELEM, + OP_OPEN_EQUIV_CLASS, + OP_CLOSE_EQUIV_CLASS, + OP_OPEN_CHAR_CLASS, + OP_CLOSE_CHAR_CLASS, + OP_WORD, + OP_NOTWORD, + OP_SPACE, + OP_NOTSPACE, + BACK_SLASH + +} re_token_type_t; + +#ifdef RE_ENABLE_I18N +typedef struct +{ + /* Multibyte characters. */ + wchar_t *mbchars; + + /* Collating symbols. */ +# ifdef _LIBC + int32_t *coll_syms; +# endif + + /* Equivalence classes. */ +# ifdef _LIBC + int32_t *equiv_classes; +# endif + + /* Range expressions. */ +# ifdef _LIBC + uint32_t *range_starts; + uint32_t *range_ends; +# else /* not _LIBC */ + wchar_t *range_starts; + wchar_t *range_ends; +# endif /* not _LIBC */ + + /* Character classes. */ + wctype_t *char_classes; + + /* If this character set is the non-matching list. */ + unsigned int non_match : 1; + + /* # of multibyte characters. */ + Idx nmbchars; + + /* # of collating symbols. */ + Idx ncoll_syms; + + /* # of equivalence classes. */ + Idx nequiv_classes; + + /* # of range expressions. */ + Idx nranges; + + /* # of character classes. */ + Idx nchar_classes; +} re_charset_t; +#endif /* RE_ENABLE_I18N */ + +typedef struct +{ + union + { + unsigned char c; /* for CHARACTER */ + re_bitset_ptr_t sbcset; /* for SIMPLE_BRACKET */ +#ifdef RE_ENABLE_I18N + re_charset_t *mbcset; /* for COMPLEX_BRACKET */ +#endif /* RE_ENABLE_I18N */ + Idx idx; /* for BACK_REF */ + re_context_type ctx_type; /* for ANCHOR */ + } opr; +#if __GNUC__ >= 2 && !__STRICT_ANSI__ + re_token_type_t type : 8; +#else + re_token_type_t type; +#endif + unsigned int constraint : 10; /* context constraint */ + unsigned int duplicated : 1; + unsigned int opt_subexp : 1; +#ifdef RE_ENABLE_I18N + unsigned int accept_mb : 1; + /* These 2 bits can be moved into the union if needed (e.g. if running out + of bits; move opr.c to opr.c.c and move the flags to opr.c.flags). */ + unsigned int mb_partial : 1; +#endif + unsigned int word_char : 1; +} re_token_t; + +#define IS_EPSILON_NODE(type) ((type) & EPSILON_BIT) + +struct re_string_t +{ + /* Indicate the raw buffer which is the original string passed as an + argument of regexec(), re_search(), etc.. */ + const unsigned char *raw_mbs; + /* Store the multibyte string. In case of "case insensitive mode" like + REG_ICASE, upper cases of the string are stored, otherwise MBS points + the same address that RAW_MBS points. */ + unsigned char *mbs; +#ifdef RE_ENABLE_I18N + /* Store the wide character string which is corresponding to MBS. */ + wint_t *wcs; + Idx *offsets; + mbstate_t cur_state; +#endif + /* Index in RAW_MBS. Each character mbs[i] corresponds to + raw_mbs[raw_mbs_idx + i]. */ + Idx raw_mbs_idx; + /* The length of the valid characters in the buffers. */ + Idx valid_len; + /* The corresponding number of bytes in raw_mbs array. */ + Idx valid_raw_len; + /* The length of the buffers MBS and WCS. */ + Idx bufs_len; + /* The index in MBS, which is updated by re_string_fetch_byte. */ + Idx cur_idx; + /* length of RAW_MBS array. */ + Idx raw_len; + /* This is RAW_LEN - RAW_MBS_IDX + VALID_LEN - VALID_RAW_LEN. */ + Idx len; + /* End of the buffer may be shorter than its length in the cases such + as re_match_2, re_search_2. Then, we use STOP for end of the buffer + instead of LEN. */ + Idx raw_stop; + /* This is RAW_STOP - RAW_MBS_IDX adjusted through OFFSETS. */ + Idx stop; + + /* The context of mbs[0]. We store the context independently, since + the context of mbs[0] may be different from raw_mbs[0], which is + the beginning of the input string. */ + unsigned int tip_context; + /* The translation passed as a part of an argument of re_compile_pattern. */ + RE_TRANSLATE_TYPE trans; + /* Copy of re_dfa_t's word_char. */ + re_const_bitset_ptr_t word_char; + /* true if REG_ICASE. */ + unsigned char icase; + unsigned char is_utf8; + unsigned char map_notascii; + unsigned char mbs_allocated; + unsigned char offsets_needed; + unsigned char newline_anchor; + unsigned char word_ops_used; + int mb_cur_max; +}; +typedef struct re_string_t re_string_t; + + +struct re_dfa_t; +typedef struct re_dfa_t re_dfa_t; + +#ifndef _LIBC +# ifdef __i386__ +# define internal_function __attribute ((regparm (3), stdcall)) +# else +# define internal_function +# endif +#endif + +static reg_errcode_t re_string_realloc_buffers (re_string_t *pstr, + Idx new_buf_len) + internal_function; +#ifdef RE_ENABLE_I18N +static void build_wcs_buffer (re_string_t *pstr) internal_function; +static reg_errcode_t build_wcs_upper_buffer (re_string_t *pstr) + internal_function; +#endif /* RE_ENABLE_I18N */ +static void build_upper_buffer (re_string_t *pstr) internal_function; +static void re_string_translate_buffer (re_string_t *pstr) internal_function; +static unsigned int re_string_context_at (const re_string_t *input, Idx idx, + int eflags) + internal_function __attribute ((pure)); +#define re_string_peek_byte(pstr, offset) \ + ((pstr)->mbs[(pstr)->cur_idx + offset]) +#define re_string_fetch_byte(pstr) \ + ((pstr)->mbs[(pstr)->cur_idx++]) +#define re_string_first_byte(pstr, idx) \ + ((idx) == (pstr)->valid_len || (pstr)->wcs[idx] != WEOF) +#define re_string_is_single_byte_char(pstr, idx) \ + ((pstr)->wcs[idx] != WEOF && ((pstr)->valid_len == (idx) + 1 \ + || (pstr)->wcs[(idx) + 1] != WEOF)) +#define re_string_eoi(pstr) ((pstr)->stop <= (pstr)->cur_idx) +#define re_string_cur_idx(pstr) ((pstr)->cur_idx) +#define re_string_get_buffer(pstr) ((pstr)->mbs) +#define re_string_length(pstr) ((pstr)->len) +#define re_string_byte_at(pstr,idx) ((pstr)->mbs[idx]) +#define re_string_skip_bytes(pstr,idx) ((pstr)->cur_idx += (idx)) +#define re_string_set_index(pstr,idx) ((pstr)->cur_idx = (idx)) + +#include + +#ifndef _LIBC +# if HAVE_ALLOCA +/* The OS usually guarantees only one guard page at the bottom of the stack, + and a page size can be as small as 4096 bytes. So we cannot safely + allocate anything larger than 4096 bytes. Also care for the possibility + of a few compiler-allocated temporary stack slots. */ +# define __libc_use_alloca(n) ((n) < 4032) +# else +/* alloca is implemented with malloc, so just use malloc. */ +# define __libc_use_alloca(n) 0 +# endif +#endif + +#ifndef MAX +# define MAX(a,b) ((a) < (b) ? (b) : (a)) +#endif + +#define re_malloc(t,n) ((t *) malloc ((n) * sizeof (t))) +#define re_realloc(p,t,n) ((t *) realloc (p, (n) * sizeof (t))) +#define re_free(p) free (p) + +struct bin_tree_t +{ + struct bin_tree_t *parent; + struct bin_tree_t *left; + struct bin_tree_t *right; + struct bin_tree_t *first; + struct bin_tree_t *next; + + re_token_t token; + + /* `node_idx' is the index in dfa->nodes, if `type' == 0. + Otherwise `type' indicate the type of this node. */ + Idx node_idx; +}; +typedef struct bin_tree_t bin_tree_t; + +#define BIN_TREE_STORAGE_SIZE \ + ((1024 - sizeof (void *)) / sizeof (bin_tree_t)) + +struct bin_tree_storage_t +{ + struct bin_tree_storage_t *next; + bin_tree_t data[BIN_TREE_STORAGE_SIZE]; +}; +typedef struct bin_tree_storage_t bin_tree_storage_t; + +#define CONTEXT_WORD 1 +#define CONTEXT_NEWLINE (CONTEXT_WORD << 1) +#define CONTEXT_BEGBUF (CONTEXT_NEWLINE << 1) +#define CONTEXT_ENDBUF (CONTEXT_BEGBUF << 1) + +#define IS_WORD_CONTEXT(c) ((c) & CONTEXT_WORD) +#define IS_NEWLINE_CONTEXT(c) ((c) & CONTEXT_NEWLINE) +#define IS_BEGBUF_CONTEXT(c) ((c) & CONTEXT_BEGBUF) +#define IS_ENDBUF_CONTEXT(c) ((c) & CONTEXT_ENDBUF) +#define IS_ORDINARY_CONTEXT(c) ((c) == 0) + +#define IS_WORD_CHAR(ch) (isalnum (ch) || (ch) == '_') +#define IS_NEWLINE(ch) ((ch) == NEWLINE_CHAR) +#define IS_WIDE_WORD_CHAR(ch) (iswalnum (ch) || (ch) == L'_') +#define IS_WIDE_NEWLINE(ch) ((ch) == WIDE_NEWLINE_CHAR) + +#define NOT_SATISFY_PREV_CONSTRAINT(constraint,context) \ + ((((constraint) & PREV_WORD_CONSTRAINT) && !IS_WORD_CONTEXT (context)) \ + || ((constraint & PREV_NOTWORD_CONSTRAINT) && IS_WORD_CONTEXT (context)) \ + || ((constraint & PREV_NEWLINE_CONSTRAINT) && !IS_NEWLINE_CONTEXT (context))\ + || ((constraint & PREV_BEGBUF_CONSTRAINT) && !IS_BEGBUF_CONTEXT (context))) + +#define NOT_SATISFY_NEXT_CONSTRAINT(constraint,context) \ + ((((constraint) & NEXT_WORD_CONSTRAINT) && !IS_WORD_CONTEXT (context)) \ + || (((constraint) & NEXT_NOTWORD_CONSTRAINT) && IS_WORD_CONTEXT (context)) \ + || (((constraint) & NEXT_NEWLINE_CONSTRAINT) && !IS_NEWLINE_CONTEXT (context)) \ + || (((constraint) & NEXT_ENDBUF_CONSTRAINT) && !IS_ENDBUF_CONTEXT (context))) + +struct re_dfastate_t +{ + re_hashval_t hash; + re_node_set nodes; + re_node_set non_eps_nodes; + re_node_set inveclosure; + re_node_set *entrance_nodes; + struct re_dfastate_t **trtable, **word_trtable; + unsigned int context : 4; + unsigned int halt : 1; + /* If this state can accept `multi byte'. + Note that we refer to multibyte characters, and multi character + collating elements as `multi byte'. */ + unsigned int accept_mb : 1; + /* If this state has backreference node(s). */ + unsigned int has_backref : 1; + unsigned int has_constraint : 1; +}; +typedef struct re_dfastate_t re_dfastate_t; + +struct re_state_table_entry +{ + Idx num; + Idx alloc; + re_dfastate_t **array; +}; + +/* Array type used in re_sub_match_last_t and re_sub_match_top_t. */ + +typedef struct +{ + Idx next_idx; + Idx alloc; + re_dfastate_t **array; +} state_array_t; + +/* Store information about the node NODE whose type is OP_CLOSE_SUBEXP. */ + +typedef struct +{ + Idx node; + Idx str_idx; /* The position NODE match at. */ + state_array_t path; +} re_sub_match_last_t; + +/* Store information about the node NODE whose type is OP_OPEN_SUBEXP. + And information about the node, whose type is OP_CLOSE_SUBEXP, + corresponding to NODE is stored in LASTS. */ + +typedef struct +{ + Idx str_idx; + Idx node; + state_array_t *path; + Idx alasts; /* Allocation size of LASTS. */ + Idx nlasts; /* The number of LASTS. */ + re_sub_match_last_t **lasts; +} re_sub_match_top_t; + +struct re_backref_cache_entry +{ + Idx node; + Idx str_idx; + Idx subexp_from; + Idx subexp_to; + char more; + char unused; + unsigned short int eps_reachable_subexps_map; +}; + +typedef struct +{ + /* The string object corresponding to the input string. */ + re_string_t input; +#if defined _LIBC || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L) + const re_dfa_t *const dfa; +#else + const re_dfa_t *dfa; +#endif + /* EFLAGS of the argument of regexec. */ + int eflags; + /* Where the matching ends. */ + Idx match_last; + Idx last_node; + /* The state log used by the matcher. */ + re_dfastate_t **state_log; + Idx state_log_top; + /* Back reference cache. */ + Idx nbkref_ents; + Idx abkref_ents; + struct re_backref_cache_entry *bkref_ents; + int max_mb_elem_len; + Idx nsub_tops; + Idx asub_tops; + re_sub_match_top_t **sub_tops; +} re_match_context_t; + +typedef struct +{ + re_dfastate_t **sifted_states; + re_dfastate_t **limited_states; + Idx last_node; + Idx last_str_idx; + re_node_set limits; +} re_sift_context_t; + +struct re_fail_stack_ent_t +{ + Idx idx; + Idx node; + regmatch_t *regs; + re_node_set eps_via_nodes; +}; + +struct re_fail_stack_t +{ + Idx num; + Idx alloc; + struct re_fail_stack_ent_t *stack; +}; + +struct re_dfa_t +{ + re_token_t *nodes; + size_t nodes_alloc; + size_t nodes_len; + Idx *nexts; + Idx *org_indices; + re_node_set *edests; + re_node_set *eclosures; + re_node_set *inveclosures; + struct re_state_table_entry *state_table; + re_dfastate_t *init_state; + re_dfastate_t *init_state_word; + re_dfastate_t *init_state_nl; + re_dfastate_t *init_state_begbuf; + bin_tree_t *str_tree; + bin_tree_storage_t *str_tree_storage; + re_bitset_ptr_t sb_char; + int str_tree_storage_idx; + + /* number of subexpressions `re_nsub' is in regex_t. */ + re_hashval_t state_hash_mask; + Idx init_node; + Idx nbackref; /* The number of backreference in this dfa. */ + + /* Bitmap expressing which backreference is used. */ + bitset_word_t used_bkref_map; + bitset_word_t completed_bkref_map; + + unsigned int has_plural_match : 1; + /* If this dfa has "multibyte node", which is a backreference or + a node which can accept multibyte character or multi character + collating element. */ + unsigned int has_mb_node : 1; + unsigned int is_utf8 : 1; + unsigned int map_notascii : 1; + unsigned int word_ops_used : 1; + int mb_cur_max; + bitset_t word_char; + reg_syntax_t syntax; + Idx *subexp_map; +#ifdef DEBUG + char* re_str; +#endif +#ifdef _LIBC + __libc_lock_define (, lock) +#endif +}; + +#define re_node_set_init_empty(set) memset (set, '\0', sizeof (re_node_set)) +#define re_node_set_remove(set,id) \ + (re_node_set_remove_at (set, re_node_set_contains (set, id) - 1)) +#define re_node_set_empty(p) ((p)->nelem = 0) +#define re_node_set_free(set) re_free ((set)->elems) + + +typedef enum +{ + SB_CHAR, + MB_CHAR, + EQUIV_CLASS, + COLL_SYM, + CHAR_CLASS +} bracket_elem_type; + +typedef struct +{ + bracket_elem_type type; + union + { + unsigned char ch; + unsigned char *name; + wchar_t wch; + } opr; +} bracket_elem_t; + + +/* Inline functions for bitset_t operation. */ + +static inline void +bitset_set (bitset_t set, Idx i) +{ + set[i / BITSET_WORD_BITS] |= (bitset_word_t) 1 << i % BITSET_WORD_BITS; +} + +static inline void +bitset_clear (bitset_t set, Idx i) +{ + set[i / BITSET_WORD_BITS] &= ~ ((bitset_word_t) 1 << i % BITSET_WORD_BITS); +} + +static inline bool +bitset_contain (const bitset_t set, Idx i) +{ + return (set[i / BITSET_WORD_BITS] >> i % BITSET_WORD_BITS) & 1; +} + +static inline void +bitset_empty (bitset_t set) +{ + memset (set, '\0', sizeof (bitset_t)); +} + +static inline void +bitset_set_all (bitset_t set) +{ + memset (set, -1, sizeof (bitset_word_t) * (SBC_MAX / BITSET_WORD_BITS)); + if (SBC_MAX % BITSET_WORD_BITS != 0) + set[BITSET_WORDS - 1] = + ((bitset_word_t) 1 << SBC_MAX % BITSET_WORD_BITS) - 1; +} + +static inline void +bitset_copy (bitset_t dest, const bitset_t src) +{ + memcpy (dest, src, sizeof (bitset_t)); +} + +static inline void +bitset_not (bitset_t set) +{ + int bitset_i; + for (bitset_i = 0; bitset_i < SBC_MAX / BITSET_WORD_BITS; ++bitset_i) + set[bitset_i] = ~set[bitset_i]; + if (SBC_MAX % BITSET_WORD_BITS != 0) + set[BITSET_WORDS - 1] = + ((((bitset_word_t) 1 << SBC_MAX % BITSET_WORD_BITS) - 1) + & ~set[BITSET_WORDS - 1]); +} + +static inline void +bitset_merge (bitset_t dest, const bitset_t src) +{ + int bitset_i; + for (bitset_i = 0; bitset_i < BITSET_WORDS; ++bitset_i) + dest[bitset_i] |= src[bitset_i]; +} + +static inline void +bitset_mask (bitset_t dest, const bitset_t src) +{ + int bitset_i; + for (bitset_i = 0; bitset_i < BITSET_WORDS; ++bitset_i) + dest[bitset_i] &= src[bitset_i]; +} + +#ifdef RE_ENABLE_I18N +/* Inline functions for re_string. */ +static inline int +internal_function __attribute ((pure)) +re_string_char_size_at (const re_string_t *pstr, Idx idx) +{ + int byte_idx; + if (pstr->mb_cur_max == 1) + return 1; + for (byte_idx = 1; idx + byte_idx < pstr->valid_len; ++byte_idx) + if (pstr->wcs[idx + byte_idx] != WEOF) + break; + return byte_idx; +} + +static inline wint_t +internal_function __attribute ((pure)) +re_string_wchar_at (const re_string_t *pstr, Idx idx) +{ + if (pstr->mb_cur_max == 1) + return (wint_t) pstr->mbs[idx]; + return (wint_t) pstr->wcs[idx]; +} + +static int +internal_function __attribute ((pure)) +re_string_elem_size_at (const re_string_t *pstr, Idx idx) +{ +# ifdef _LIBC + const unsigned char *p, *extra; + const int32_t *table, *indirect; + int32_t tmp; +# include + uint_fast32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES); + + if (nrules != 0) + { + table = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB); + extra = (const unsigned char *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB); + indirect = (const int32_t *) _NL_CURRENT (LC_COLLATE, + _NL_COLLATE_INDIRECTMB); + p = pstr->mbs + idx; + tmp = findidx (&p); + return p - pstr->mbs - idx; + } + else +# endif /* _LIBC */ + return 1; +} +#endif /* RE_ENABLE_I18N */ + +#endif /* _REGEX_INTERNAL_H */ diff --git a/src/bin/findutils/gnulib/lib/regexec.c b/src/bin/findutils/gnulib/lib/regexec.c new file mode 100644 index 0000000000..ac6c258e71 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/regexec.c @@ -0,0 +1,4399 @@ +/* Extended regular expression matching and search library. + Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, + Inc. + This file is part of the GNU C Library. + Contributed by Isamu Hasegawa . + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +static reg_errcode_t match_ctx_init (re_match_context_t *cache, int eflags, + Idx n) internal_function; +static void match_ctx_clean (re_match_context_t *mctx) internal_function; +static void match_ctx_free (re_match_context_t *cache) internal_function; +static reg_errcode_t match_ctx_add_entry (re_match_context_t *cache, Idx node, + Idx str_idx, Idx from, Idx to) + internal_function; +static Idx search_cur_bkref_entry (const re_match_context_t *mctx, Idx str_idx) + internal_function; +static reg_errcode_t match_ctx_add_subtop (re_match_context_t *mctx, Idx node, + Idx str_idx) internal_function; +static re_sub_match_last_t * match_ctx_add_sublast (re_sub_match_top_t *subtop, + Idx node, Idx str_idx) + internal_function; +static void sift_ctx_init (re_sift_context_t *sctx, re_dfastate_t **sifted_sts, + re_dfastate_t **limited_sts, Idx last_node, + Idx last_str_idx) + internal_function; +static reg_errcode_t re_search_internal (const regex_t *preg, + const char *string, Idx length, + Idx start, Idx last_start, Idx stop, + size_t nmatch, regmatch_t pmatch[], + int eflags) internal_function; +static regoff_t re_search_2_stub (struct re_pattern_buffer *bufp, + const char *string1, Idx length1, + const char *string2, Idx length2, + Idx start, regoff_t range, + struct re_registers *regs, + Idx stop, bool ret_len) internal_function; +static regoff_t re_search_stub (struct re_pattern_buffer *bufp, + const char *string, Idx length, Idx start, + regoff_t range, Idx stop, + struct re_registers *regs, + bool ret_len) internal_function; +static unsigned int re_copy_regs (struct re_registers *regs, regmatch_t *pmatch, + Idx nregs, int regs_allocated) + internal_function; +static reg_errcode_t prune_impossible_nodes (re_match_context_t *mctx) + internal_function; +static Idx check_matching (re_match_context_t *mctx, bool fl_longest_match, + Idx *p_match_first) internal_function; +static Idx check_halt_state_context (const re_match_context_t *mctx, + const re_dfastate_t *state, Idx idx) + internal_function; +static void update_regs (const re_dfa_t *dfa, regmatch_t *pmatch, + regmatch_t *prev_idx_match, Idx cur_node, + Idx cur_idx, Idx nmatch) internal_function; +static reg_errcode_t push_fail_stack (struct re_fail_stack_t *fs, + Idx str_idx, Idx dest_node, Idx nregs, + regmatch_t *regs, + re_node_set *eps_via_nodes) + internal_function; +static reg_errcode_t set_regs (const regex_t *preg, + const re_match_context_t *mctx, + size_t nmatch, regmatch_t *pmatch, + bool fl_backtrack) internal_function; +static reg_errcode_t free_fail_stack_return (struct re_fail_stack_t *fs) + internal_function; + +#ifdef RE_ENABLE_I18N +static int sift_states_iter_mb (const re_match_context_t *mctx, + re_sift_context_t *sctx, + Idx node_idx, Idx str_idx, Idx max_str_idx) + internal_function; +#endif /* RE_ENABLE_I18N */ +static reg_errcode_t sift_states_backward (const re_match_context_t *mctx, + re_sift_context_t *sctx) + internal_function; +static reg_errcode_t build_sifted_states (const re_match_context_t *mctx, + re_sift_context_t *sctx, Idx str_idx, + re_node_set *cur_dest) + internal_function; +static reg_errcode_t update_cur_sifted_state (const re_match_context_t *mctx, + re_sift_context_t *sctx, + Idx str_idx, + re_node_set *dest_nodes) + internal_function; +static reg_errcode_t add_epsilon_src_nodes (const re_dfa_t *dfa, + re_node_set *dest_nodes, + const re_node_set *candidates) + internal_function; +static bool check_dst_limits (const re_match_context_t *mctx, + const re_node_set *limits, + Idx dst_node, Idx dst_idx, Idx src_node, + Idx src_idx) internal_function; +static int check_dst_limits_calc_pos_1 (const re_match_context_t *mctx, + int boundaries, Idx subexp_idx, + Idx from_node, Idx bkref_idx) + internal_function; +static int check_dst_limits_calc_pos (const re_match_context_t *mctx, + Idx limit, Idx subexp_idx, + Idx node, Idx str_idx, + Idx bkref_idx) internal_function; +static reg_errcode_t check_subexp_limits (const re_dfa_t *dfa, + re_node_set *dest_nodes, + const re_node_set *candidates, + re_node_set *limits, + struct re_backref_cache_entry *bkref_ents, + Idx str_idx) internal_function; +static reg_errcode_t sift_states_bkref (const re_match_context_t *mctx, + re_sift_context_t *sctx, + Idx str_idx, const re_node_set *candidates) + internal_function; +static reg_errcode_t merge_state_array (const re_dfa_t *dfa, + re_dfastate_t **dst, + re_dfastate_t **src, Idx num) + internal_function; +static re_dfastate_t *find_recover_state (reg_errcode_t *err, + re_match_context_t *mctx) internal_function; +static re_dfastate_t *transit_state (reg_errcode_t *err, + re_match_context_t *mctx, + re_dfastate_t *state) internal_function; +static re_dfastate_t *merge_state_with_log (reg_errcode_t *err, + re_match_context_t *mctx, + re_dfastate_t *next_state) + internal_function; +static reg_errcode_t check_subexp_matching_top (re_match_context_t *mctx, + re_node_set *cur_nodes, + Idx str_idx) internal_function; +#if 0 +static re_dfastate_t *transit_state_sb (reg_errcode_t *err, + re_match_context_t *mctx, + re_dfastate_t *pstate) + internal_function; +#endif +#ifdef RE_ENABLE_I18N +static reg_errcode_t transit_state_mb (re_match_context_t *mctx, + re_dfastate_t *pstate) + internal_function; +#endif /* RE_ENABLE_I18N */ +static reg_errcode_t transit_state_bkref (re_match_context_t *mctx, + const re_node_set *nodes) + internal_function; +static reg_errcode_t get_subexp (re_match_context_t *mctx, + Idx bkref_node, Idx bkref_str_idx) + internal_function; +static reg_errcode_t get_subexp_sub (re_match_context_t *mctx, + const re_sub_match_top_t *sub_top, + re_sub_match_last_t *sub_last, + Idx bkref_node, Idx bkref_str) + internal_function; +static Idx find_subexp_node (const re_dfa_t *dfa, const re_node_set *nodes, + Idx subexp_idx, int type) internal_function; +static reg_errcode_t check_arrival (re_match_context_t *mctx, + state_array_t *path, Idx top_node, + Idx top_str, Idx last_node, Idx last_str, + int type) internal_function; +static reg_errcode_t check_arrival_add_next_nodes (re_match_context_t *mctx, + Idx str_idx, + re_node_set *cur_nodes, + re_node_set *next_nodes) + internal_function; +static reg_errcode_t check_arrival_expand_ecl (const re_dfa_t *dfa, + re_node_set *cur_nodes, + Idx ex_subexp, int type) + internal_function; +static reg_errcode_t check_arrival_expand_ecl_sub (const re_dfa_t *dfa, + re_node_set *dst_nodes, + Idx target, Idx ex_subexp, + int type) internal_function; +static reg_errcode_t expand_bkref_cache (re_match_context_t *mctx, + re_node_set *cur_nodes, Idx cur_str, + Idx subexp_num, int type) + internal_function; +static bool build_trtable (const re_dfa_t *dfa, + re_dfastate_t *state) internal_function; +#ifdef RE_ENABLE_I18N +static int check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx, + const re_string_t *input, Idx idx) + internal_function; +# ifdef _LIBC +static unsigned int find_collation_sequence_value (const unsigned char *mbs, + size_t name_len) + internal_function; +# endif /* _LIBC */ +#endif /* RE_ENABLE_I18N */ +static Idx group_nodes_into_DFAstates (const re_dfa_t *dfa, + const re_dfastate_t *state, + re_node_set *states_node, + bitset_t *states_ch) internal_function; +static bool check_node_accept (const re_match_context_t *mctx, + const re_token_t *node, Idx idx) + internal_function; +static reg_errcode_t extend_buffers (re_match_context_t *mctx) + internal_function; + +/* Entry point for POSIX code. */ + +/* regexec searches for a given pattern, specified by PREG, in the + string STRING. + + If NMATCH is zero or REG_NOSUB was set in the cflags argument to + `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at + least NMATCH elements, and we set them to the offsets of the + corresponding matched substrings. + + EFLAGS specifies `execution flags' which affect matching: if + REG_NOTBOL is set, then ^ does not match at the beginning of the + string; if REG_NOTEOL is set, then $ does not match at the end. + + We return 0 if we find a match and REG_NOMATCH if not. */ + +int +regexec (preg, string, nmatch, pmatch, eflags) + const regex_t *_Restrict_ preg; + const char *_Restrict_ string; + size_t nmatch; + regmatch_t pmatch[_Restrict_arr_]; + int eflags; +{ + reg_errcode_t err; + Idx start, length; +#ifdef _LIBC + re_dfa_t *dfa = (re_dfa_t *) preg->buffer; +#endif + + if (eflags & ~(REG_NOTBOL | REG_NOTEOL | REG_STARTEND)) + return REG_BADPAT; + + if (eflags & REG_STARTEND) + { + start = pmatch[0].rm_so; + length = pmatch[0].rm_eo; + } + else + { + start = 0; + length = strlen (string); + } + + __libc_lock_lock (dfa->lock); + if (preg->no_sub) + err = re_search_internal (preg, string, length, start, length, + length, 0, NULL, eflags); + else + err = re_search_internal (preg, string, length, start, length, + length, nmatch, pmatch, eflags); + __libc_lock_unlock (dfa->lock); + return err != REG_NOERROR; +} + +#ifdef _LIBC +# include +versioned_symbol (libc, __regexec, regexec, GLIBC_2_3_4); + +# if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_3_4) +__typeof__ (__regexec) __compat_regexec; + +int +attribute_compat_text_section +__compat_regexec (const regex_t *_Restrict_ preg, + const char *_Restrict_ string, size_t nmatch, + regmatch_t pmatch[], int eflags) +{ + return regexec (preg, string, nmatch, pmatch, + eflags & (REG_NOTBOL | REG_NOTEOL)); +} +compat_symbol (libc, __compat_regexec, regexec, GLIBC_2_0); +# endif +#endif + +/* Entry points for GNU code. */ + +/* re_match, re_search, re_match_2, re_search_2 + + The former two functions operate on STRING with length LENGTH, + while the later two operate on concatenation of STRING1 and STRING2 + with lengths LENGTH1 and LENGTH2, respectively. + + re_match() matches the compiled pattern in BUFP against the string, + starting at index START. + + re_search() first tries matching at index START, then it tries to match + starting from index START + 1, and so on. The last start position tried + is START + RANGE. (Thus RANGE = 0 forces re_search to operate the same + way as re_match().) + + The parameter STOP of re_{match,search}_2 specifies that no match exceeding + the first STOP characters of the concatenation of the strings should be + concerned. + + If REGS is not NULL, and BUFP->no_sub is not set, the offsets of the match + and all groups is stored in REGS. (For the "_2" variants, the offsets are + computed relative to the concatenation, not relative to the individual + strings.) + + On success, re_match* functions return the length of the match, re_search* + return the position of the start of the match. Return value -1 means no + match was found and -2 indicates an internal error. */ + +regoff_t +re_match (bufp, string, length, start, regs) + struct re_pattern_buffer *bufp; + const char *string; + Idx length, start; + struct re_registers *regs; +{ + return re_search_stub (bufp, string, length, start, 0, length, regs, true); +} +#ifdef _LIBC +weak_alias (__re_match, re_match) +#endif + +regoff_t +re_search (bufp, string, length, start, range, regs) + struct re_pattern_buffer *bufp; + const char *string; + Idx length, start; + regoff_t range; + struct re_registers *regs; +{ + return re_search_stub (bufp, string, length, start, range, length, regs, + false); +} +#ifdef _LIBC +weak_alias (__re_search, re_search) +#endif + +regoff_t +re_match_2 (bufp, string1, length1, string2, length2, start, regs, stop) + struct re_pattern_buffer *bufp; + const char *string1, *string2; + Idx length1, length2, start, stop; + struct re_registers *regs; +{ + return re_search_2_stub (bufp, string1, length1, string2, length2, + start, 0, regs, stop, true); +} +#ifdef _LIBC +weak_alias (__re_match_2, re_match_2) +#endif + +regoff_t +re_search_2 (bufp, string1, length1, string2, length2, start, range, regs, stop) + struct re_pattern_buffer *bufp; + const char *string1, *string2; + Idx length1, length2, start, stop; + regoff_t range; + struct re_registers *regs; +{ + return re_search_2_stub (bufp, string1, length1, string2, length2, + start, range, regs, stop, false); +} +#ifdef _LIBC +weak_alias (__re_search_2, re_search_2) +#endif + +static regoff_t +internal_function +re_search_2_stub (struct re_pattern_buffer *bufp, + const char *string1, Idx length1, + const char *string2, Idx length2, + Idx start, regoff_t range, struct re_registers *regs, + Idx stop, bool ret_len) +{ + const char *str; + regoff_t rval; + Idx len = length1 + length2; + char *s = NULL; + + if (BE (length1 < 0 || length2 < 0 || stop < 0 || len < length1, 0)) + return -2; + + /* Concatenate the strings. */ + if (length2 > 0) + if (length1 > 0) + { + s = re_malloc (char, len); + + if (BE (s == NULL, 0)) + return -2; +#ifdef _LIBC + memcpy (__mempcpy (s, string1, length1), string2, length2); +#else + memcpy (s, string1, length1); + memcpy (s + length1, string2, length2); +#endif + str = s; + } + else + str = string2; + else + str = string1; + + rval = re_search_stub (bufp, str, len, start, range, stop, regs, + ret_len); + re_free (s); + return rval; +} + +/* The parameters have the same meaning as those of re_search. + Additional parameters: + If RET_LEN is true the length of the match is returned (re_match style); + otherwise the position of the match is returned. */ + +static regoff_t +internal_function +re_search_stub (struct re_pattern_buffer *bufp, + const char *string, Idx length, + Idx start, regoff_t range, Idx stop, struct re_registers *regs, + bool ret_len) +{ + reg_errcode_t result; + regmatch_t *pmatch; + Idx nregs; + regoff_t rval; + int eflags = 0; +#ifdef _LIBC + re_dfa_t *dfa = (re_dfa_t *) bufp->buffer; +#endif + Idx last_start = start + range; + + /* Check for out-of-range. */ + if (BE (start < 0 || start > length, 0)) + return -1; + if (BE (length < last_start || (0 <= range && last_start < start), 0)) + last_start = length; + else if (BE (last_start < 0 || (range < 0 && start <= last_start), 0)) + last_start = 0; + + __libc_lock_lock (dfa->lock); + + eflags |= (bufp->not_bol) ? REG_NOTBOL : 0; + eflags |= (bufp->not_eol) ? REG_NOTEOL : 0; + + /* Compile fastmap if we haven't yet. */ + if (start < last_start && bufp->fastmap != NULL && !bufp->fastmap_accurate) + re_compile_fastmap (bufp); + + if (BE (bufp->no_sub, 0)) + regs = NULL; + + /* We need at least 1 register. */ + if (regs == NULL) + nregs = 1; + else if (BE (bufp->regs_allocated == REGS_FIXED + && regs->num_regs <= bufp->re_nsub, 0)) + { + nregs = regs->num_regs; + if (BE (nregs < 1, 0)) + { + /* Nothing can be copied to regs. */ + regs = NULL; + nregs = 1; + } + } + else + nregs = bufp->re_nsub + 1; + pmatch = re_malloc (regmatch_t, nregs); + if (BE (pmatch == NULL, 0)) + { + rval = -2; + goto out; + } + + result = re_search_internal (bufp, string, length, start, last_start, stop, + nregs, pmatch, eflags); + + rval = 0; + + /* I hope we needn't fill ther regs with -1's when no match was found. */ + if (result != REG_NOERROR) + rval = -1; + else if (regs != NULL) + { + /* If caller wants register contents data back, copy them. */ + bufp->regs_allocated = re_copy_regs (regs, pmatch, nregs, + bufp->regs_allocated); + if (BE (bufp->regs_allocated == REGS_UNALLOCATED, 0)) + rval = -2; + } + + if (BE (rval == 0, 1)) + { + if (ret_len) + { + assert (pmatch[0].rm_so == start); + rval = pmatch[0].rm_eo - start; + } + else + rval = pmatch[0].rm_so; + } + re_free (pmatch); + out: + __libc_lock_unlock (dfa->lock); + return rval; +} + +static unsigned int +internal_function +re_copy_regs (struct re_registers *regs, regmatch_t *pmatch, Idx nregs, + int regs_allocated) +{ + int rval = REGS_REALLOCATE; + Idx i; + Idx need_regs = nregs + 1; + /* We need one extra element beyond `num_regs' for the `-1' marker GNU code + uses. */ + + /* Have the register data arrays been allocated? */ + if (regs_allocated == REGS_UNALLOCATED) + { /* No. So allocate them with malloc. */ + regs->start = re_malloc (regoff_t, need_regs); + if (BE (regs->start == NULL, 0)) + return REGS_UNALLOCATED; + regs->end = re_malloc (regoff_t, need_regs); + if (BE (regs->end == NULL, 0)) + { + re_free (regs->start); + return REGS_UNALLOCATED; + } + regs->num_regs = need_regs; + } + else if (regs_allocated == REGS_REALLOCATE) + { /* Yes. If we need more elements than were already + allocated, reallocate them. If we need fewer, just + leave it alone. */ + if (BE (need_regs > regs->num_regs, 0)) + { + regoff_t *new_start = re_realloc (regs->start, regoff_t, need_regs); + regoff_t *new_end; + if (BE (new_start == NULL, 0)) + return REGS_UNALLOCATED; + new_end = re_realloc (regs->end, regoff_t, need_regs); + if (BE (new_end == NULL, 0)) + { + re_free (new_start); + return REGS_UNALLOCATED; + } + regs->start = new_start; + regs->end = new_end; + regs->num_regs = need_regs; + } + } + else + { + assert (regs_allocated == REGS_FIXED); + /* This function may not be called with REGS_FIXED and nregs too big. */ + assert (regs->num_regs >= nregs); + rval = REGS_FIXED; + } + + /* Copy the regs. */ + for (i = 0; i < nregs; ++i) + { + regs->start[i] = pmatch[i].rm_so; + regs->end[i] = pmatch[i].rm_eo; + } + for ( ; i < regs->num_regs; ++i) + regs->start[i] = regs->end[i] = -1; + + return rval; +} + +/* Set REGS to hold NUM_REGS registers, storing them in STARTS and + ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use + this memory for recording register information. STARTS and ENDS + must be allocated using the malloc library routine, and must each + be at least NUM_REGS * sizeof (regoff_t) bytes long. + + If NUM_REGS == 0, then subsequent matches should allocate their own + register data. + + Unless this function is called, the first search or match using + PATTERN_BUFFER will allocate its own register data, without + freeing the old data. */ + +void +re_set_registers (bufp, regs, num_regs, starts, ends) + struct re_pattern_buffer *bufp; + struct re_registers *regs; + __re_size_t num_regs; + regoff_t *starts, *ends; +{ + if (num_regs) + { + bufp->regs_allocated = REGS_REALLOCATE; + regs->num_regs = num_regs; + regs->start = starts; + regs->end = ends; + } + else + { + bufp->regs_allocated = REGS_UNALLOCATED; + regs->num_regs = 0; + regs->start = regs->end = NULL; + } +} +#ifdef _LIBC +weak_alias (__re_set_registers, re_set_registers) +#endif + +/* Entry points compatible with 4.2 BSD regex library. We don't define + them unless specifically requested. */ + +#if defined _REGEX_RE_COMP || defined _LIBC +int +# ifdef _LIBC +weak_function +# endif +re_exec (s) + const char *s; +{ + return 0 == regexec (&re_comp_buf, s, 0, NULL, 0); +} +#endif /* _REGEX_RE_COMP */ + +/* Internal entry point. */ + +/* Searches for a compiled pattern PREG in the string STRING, whose + length is LENGTH. NMATCH, PMATCH, and EFLAGS have the same + meaning as with regexec. LAST_START is START + RANGE, where + START and RANGE have the same meaning as with re_search. + Return REG_NOERROR if we find a match, and REG_NOMATCH if not, + otherwise return the error code. + Note: We assume front end functions already check ranges. + (0 <= LAST_START && LAST_START <= LENGTH) */ + +static reg_errcode_t +internal_function +re_search_internal (const regex_t *preg, + const char *string, Idx length, + Idx start, Idx last_start, Idx stop, + size_t nmatch, regmatch_t pmatch[], + int eflags) +{ + reg_errcode_t err; + const re_dfa_t *dfa = (const re_dfa_t *) preg->buffer; + Idx left_lim, right_lim; + int incr; + bool fl_longest_match; + int match_kind; + Idx match_first; + Idx match_last = REG_MISSING; + Idx extra_nmatch; + bool sb; + int ch; +#if defined _LIBC || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L) + re_match_context_t mctx = { .dfa = dfa }; +#else + re_match_context_t mctx; +#endif + char *fastmap = ((preg->fastmap != NULL && preg->fastmap_accurate + && start != last_start && !preg->can_be_null) + ? preg->fastmap : NULL); + RE_TRANSLATE_TYPE t = preg->translate; + +#if !(defined _LIBC || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L)) + memset (&mctx, '\0', sizeof (re_match_context_t)); + mctx.dfa = dfa; +#endif + + extra_nmatch = (nmatch > preg->re_nsub) ? nmatch - (preg->re_nsub + 1) : 0; + nmatch -= extra_nmatch; + + /* Check if the DFA haven't been compiled. */ + if (BE (preg->used == 0 || dfa->init_state == NULL + || dfa->init_state_word == NULL || dfa->init_state_nl == NULL + || dfa->init_state_begbuf == NULL, 0)) + return REG_NOMATCH; + +#ifdef DEBUG + /* We assume front-end functions already check them. */ + assert (0 <= last_start && last_start <= length); +#endif + + /* If initial states with non-begbuf contexts have no elements, + the regex must be anchored. If preg->newline_anchor is set, + we'll never use init_state_nl, so do not check it. */ + if (dfa->init_state->nodes.nelem == 0 + && dfa->init_state_word->nodes.nelem == 0 + && (dfa->init_state_nl->nodes.nelem == 0 + || !preg->newline_anchor)) + { + if (start != 0 && last_start != 0) + return REG_NOMATCH; + start = last_start = 0; + } + + /* We must check the longest matching, if nmatch > 0. */ + fl_longest_match = (nmatch != 0 || dfa->nbackref); + + err = re_string_allocate (&mctx.input, string, length, dfa->nodes_len + 1, + preg->translate, preg->syntax & RE_ICASE, dfa); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + mctx.input.stop = stop; + mctx.input.raw_stop = stop; + mctx.input.newline_anchor = preg->newline_anchor; + + err = match_ctx_init (&mctx, eflags, dfa->nbackref * 2); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + + /* We will log all the DFA states through which the dfa pass, + if nmatch > 1, or this dfa has "multibyte node", which is a + back-reference or a node which can accept multibyte character or + multi character collating element. */ + if (nmatch > 1 || dfa->has_mb_node) + { + /* Avoid overflow. */ + if (BE (SIZE_MAX / sizeof (re_dfastate_t *) <= mctx.input.bufs_len, 0)) + { + err = REG_ESPACE; + goto free_return; + } + + mctx.state_log = re_malloc (re_dfastate_t *, mctx.input.bufs_len + 1); + if (BE (mctx.state_log == NULL, 0)) + { + err = REG_ESPACE; + goto free_return; + } + } + else + mctx.state_log = NULL; + + match_first = start; + mctx.input.tip_context = (eflags & REG_NOTBOL) ? CONTEXT_BEGBUF + : CONTEXT_NEWLINE | CONTEXT_BEGBUF; + + /* Check incrementally whether of not the input string match. */ + incr = (last_start < start) ? -1 : 1; + left_lim = (last_start < start) ? last_start : start; + right_lim = (last_start < start) ? start : last_start; + sb = dfa->mb_cur_max == 1; + match_kind = + (fastmap + ? ((sb || !(preg->syntax & RE_ICASE || t) ? 4 : 0) + | (start <= last_start ? 2 : 0) + | (t != NULL ? 1 : 0)) + : 8); + + for (;; match_first += incr) + { + err = REG_NOMATCH; + if (match_first < left_lim || right_lim < match_first) + goto free_return; + + /* Advance as rapidly as possible through the string, until we + find a plausible place to start matching. This may be done + with varying efficiency, so there are various possibilities: + only the most common of them are specialized, in order to + save on code size. We use a switch statement for speed. */ + switch (match_kind) + { + case 8: + /* No fastmap. */ + break; + + case 7: + /* Fastmap with single-byte translation, match forward. */ + while (BE (match_first < right_lim, 1) + && !fastmap[t[(unsigned char) string[match_first]]]) + ++match_first; + goto forward_match_found_start_or_reached_end; + + case 6: + /* Fastmap without translation, match forward. */ + while (BE (match_first < right_lim, 1) + && !fastmap[(unsigned char) string[match_first]]) + ++match_first; + + forward_match_found_start_or_reached_end: + if (BE (match_first == right_lim, 0)) + { + ch = match_first >= length + ? 0 : (unsigned char) string[match_first]; + if (!fastmap[t ? t[ch] : ch]) + goto free_return; + } + break; + + case 4: + case 5: + /* Fastmap without multi-byte translation, match backwards. */ + while (match_first >= left_lim) + { + ch = match_first >= length + ? 0 : (unsigned char) string[match_first]; + if (fastmap[t ? t[ch] : ch]) + break; + --match_first; + } + if (match_first < left_lim) + goto free_return; + break; + + default: + /* In this case, we can't determine easily the current byte, + since it might be a component byte of a multibyte + character. Then we use the constructed buffer instead. */ + for (;;) + { + /* If MATCH_FIRST is out of the valid range, reconstruct the + buffers. */ + __re_size_t offset = match_first - mctx.input.raw_mbs_idx; + if (BE (offset >= (__re_size_t) mctx.input.valid_raw_len, 0)) + { + err = re_string_reconstruct (&mctx.input, match_first, + eflags); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + + offset = match_first - mctx.input.raw_mbs_idx; + } + /* If MATCH_FIRST is out of the buffer, leave it as '\0'. + Note that MATCH_FIRST must not be smaller than 0. */ + ch = (match_first >= length + ? 0 : re_string_byte_at (&mctx.input, offset)); + if (fastmap[ch]) + break; + match_first += incr; + if (match_first < left_lim || match_first > right_lim) + { + err = REG_NOMATCH; + goto free_return; + } + } + break; + } + + /* Reconstruct the buffers so that the matcher can assume that + the matching starts from the beginning of the buffer. */ + err = re_string_reconstruct (&mctx.input, match_first, eflags); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + +#ifdef RE_ENABLE_I18N + /* Don't consider this char as a possible match start if it part, + yet isn't the head, of a multibyte character. */ + if (!sb && !re_string_first_byte (&mctx.input, 0)) + continue; +#endif + + /* It seems to be appropriate one, then use the matcher. */ + /* We assume that the matching starts from 0. */ + mctx.state_log_top = mctx.nbkref_ents = mctx.max_mb_elem_len = 0; + match_last = check_matching (&mctx, fl_longest_match, + start <= last_start ? &match_first : NULL); + if (match_last != REG_MISSING) + { + if (BE (match_last == REG_ERROR, 0)) + { + err = REG_ESPACE; + goto free_return; + } + else + { + mctx.match_last = match_last; + if ((!preg->no_sub && nmatch > 1) || dfa->nbackref) + { + re_dfastate_t *pstate = mctx.state_log[match_last]; + mctx.last_node = check_halt_state_context (&mctx, pstate, + match_last); + } + if ((!preg->no_sub && nmatch > 1 && dfa->has_plural_match) + || dfa->nbackref) + { + err = prune_impossible_nodes (&mctx); + if (err == REG_NOERROR) + break; + if (BE (err != REG_NOMATCH, 0)) + goto free_return; + match_last = REG_MISSING; + } + else + break; /* We found a match. */ + } + } + + match_ctx_clean (&mctx); + } + +#ifdef DEBUG + assert (match_last != REG_MISSING); + assert (err == REG_NOERROR); +#endif + + /* Set pmatch[] if we need. */ + if (nmatch > 0) + { + Idx reg_idx; + + /* Initialize registers. */ + for (reg_idx = 1; reg_idx < nmatch; ++reg_idx) + pmatch[reg_idx].rm_so = pmatch[reg_idx].rm_eo = -1; + + /* Set the points where matching start/end. */ + pmatch[0].rm_so = 0; + pmatch[0].rm_eo = mctx.match_last; + /* FIXME: This function should fail if mctx.match_last exceeds + the maximum possible regoff_t value. We need a new error + code REG_OVERFLOW. */ + + if (!preg->no_sub && nmatch > 1) + { + err = set_regs (preg, &mctx, nmatch, pmatch, + dfa->has_plural_match && dfa->nbackref > 0); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + } + + /* At last, add the offset to the each registers, since we slided + the buffers so that we could assume that the matching starts + from 0. */ + for (reg_idx = 0; reg_idx < nmatch; ++reg_idx) + if (pmatch[reg_idx].rm_so != -1) + { +#ifdef RE_ENABLE_I18N + if (BE (mctx.input.offsets_needed != 0, 0)) + { + pmatch[reg_idx].rm_so = + (pmatch[reg_idx].rm_so == mctx.input.valid_len + ? mctx.input.valid_raw_len + : mctx.input.offsets[pmatch[reg_idx].rm_so]); + pmatch[reg_idx].rm_eo = + (pmatch[reg_idx].rm_eo == mctx.input.valid_len + ? mctx.input.valid_raw_len + : mctx.input.offsets[pmatch[reg_idx].rm_eo]); + } +#else + assert (mctx.input.offsets_needed == 0); +#endif + pmatch[reg_idx].rm_so += match_first; + pmatch[reg_idx].rm_eo += match_first; + } + for (reg_idx = 0; reg_idx < extra_nmatch; ++reg_idx) + { + pmatch[nmatch + reg_idx].rm_so = -1; + pmatch[nmatch + reg_idx].rm_eo = -1; + } + + if (dfa->subexp_map) + for (reg_idx = 0; reg_idx + 1 < nmatch; reg_idx++) + if (dfa->subexp_map[reg_idx] != reg_idx) + { + pmatch[reg_idx + 1].rm_so + = pmatch[dfa->subexp_map[reg_idx] + 1].rm_so; + pmatch[reg_idx + 1].rm_eo + = pmatch[dfa->subexp_map[reg_idx] + 1].rm_eo; + } + } + + free_return: + re_free (mctx.state_log); + if (dfa->nbackref) + match_ctx_free (&mctx); + re_string_destruct (&mctx.input); + return err; +} + +static reg_errcode_t +internal_function +prune_impossible_nodes (re_match_context_t *mctx) +{ + const re_dfa_t *const dfa = mctx->dfa; + Idx halt_node, match_last; + reg_errcode_t ret; + re_dfastate_t **sifted_states; + re_dfastate_t **lim_states = NULL; + re_sift_context_t sctx; +#ifdef DEBUG + assert (mctx->state_log != NULL); +#endif + match_last = mctx->match_last; + halt_node = mctx->last_node; + + /* Avoid overflow. */ + if (BE (SIZE_MAX / sizeof (re_dfastate_t *) <= match_last, 0)) + return REG_ESPACE; + + sifted_states = re_malloc (re_dfastate_t *, match_last + 1); + if (BE (sifted_states == NULL, 0)) + { + ret = REG_ESPACE; + goto free_return; + } + if (dfa->nbackref) + { + lim_states = re_malloc (re_dfastate_t *, match_last + 1); + if (BE (lim_states == NULL, 0)) + { + ret = REG_ESPACE; + goto free_return; + } + while (1) + { + memset (lim_states, '\0', + sizeof (re_dfastate_t *) * (match_last + 1)); + sift_ctx_init (&sctx, sifted_states, lim_states, halt_node, + match_last); + ret = sift_states_backward (mctx, &sctx); + re_node_set_free (&sctx.limits); + if (BE (ret != REG_NOERROR, 0)) + goto free_return; + if (sifted_states[0] != NULL || lim_states[0] != NULL) + break; + do + { + --match_last; + if (! REG_VALID_INDEX (match_last)) + { + ret = REG_NOMATCH; + goto free_return; + } + } while (mctx->state_log[match_last] == NULL + || !mctx->state_log[match_last]->halt); + halt_node = check_halt_state_context (mctx, + mctx->state_log[match_last], + match_last); + } + ret = merge_state_array (dfa, sifted_states, lim_states, + match_last + 1); + re_free (lim_states); + lim_states = NULL; + if (BE (ret != REG_NOERROR, 0)) + goto free_return; + } + else + { + sift_ctx_init (&sctx, sifted_states, lim_states, halt_node, match_last); + ret = sift_states_backward (mctx, &sctx); + re_node_set_free (&sctx.limits); + if (BE (ret != REG_NOERROR, 0)) + goto free_return; + } + re_free (mctx->state_log); + mctx->state_log = sifted_states; + sifted_states = NULL; + mctx->last_node = halt_node; + mctx->match_last = match_last; + ret = REG_NOERROR; + free_return: + re_free (sifted_states); + re_free (lim_states); + return ret; +} + +/* Acquire an initial state and return it. + We must select appropriate initial state depending on the context, + since initial states may have constraints like "\<", "^", etc.. */ + +static inline re_dfastate_t * +__attribute ((always_inline)) internal_function +acquire_init_state_context (reg_errcode_t *err, const re_match_context_t *mctx, + Idx idx) +{ + const re_dfa_t *const dfa = mctx->dfa; + if (dfa->init_state->has_constraint) + { + unsigned int context; + context = re_string_context_at (&mctx->input, idx - 1, mctx->eflags); + if (IS_WORD_CONTEXT (context)) + return dfa->init_state_word; + else if (IS_ORDINARY_CONTEXT (context)) + return dfa->init_state; + else if (IS_BEGBUF_CONTEXT (context) && IS_NEWLINE_CONTEXT (context)) + return dfa->init_state_begbuf; + else if (IS_NEWLINE_CONTEXT (context)) + return dfa->init_state_nl; + else if (IS_BEGBUF_CONTEXT (context)) + { + /* It is relatively rare case, then calculate on demand. */ + return re_acquire_state_context (err, dfa, + dfa->init_state->entrance_nodes, + context); + } + else + /* Must not happen? */ + return dfa->init_state; + } + else + return dfa->init_state; +} + +/* Check whether the regular expression match input string INPUT or not, + and return the index where the matching end. Return REG_MISSING if + there is no match, and return REG_ERROR in case of an error. + FL_LONGEST_MATCH means we want the POSIX longest matching. + If P_MATCH_FIRST is not NULL, and the match fails, it is set to the + next place where we may want to try matching. + Note that the matcher assume that the maching starts from the current + index of the buffer. */ + +static Idx +internal_function +check_matching (re_match_context_t *mctx, bool fl_longest_match, + Idx *p_match_first) +{ + const re_dfa_t *const dfa = mctx->dfa; + reg_errcode_t err; + Idx match = 0; + Idx match_last = REG_MISSING; + Idx cur_str_idx = re_string_cur_idx (&mctx->input); + re_dfastate_t *cur_state; + bool at_init_state = p_match_first != NULL; + Idx next_start_idx = cur_str_idx; + + err = REG_NOERROR; + cur_state = acquire_init_state_context (&err, mctx, cur_str_idx); + /* An initial state must not be NULL (invalid). */ + if (BE (cur_state == NULL, 0)) + { + assert (err == REG_ESPACE); + return REG_ERROR; + } + + if (mctx->state_log != NULL) + { + mctx->state_log[cur_str_idx] = cur_state; + + /* Check OP_OPEN_SUBEXP in the initial state in case that we use them + later. E.g. Processing back references. */ + if (BE (dfa->nbackref, 0)) + { + at_init_state = false; + err = check_subexp_matching_top (mctx, &cur_state->nodes, 0); + if (BE (err != REG_NOERROR, 0)) + return err; + + if (cur_state->has_backref) + { + err = transit_state_bkref (mctx, &cur_state->nodes); + if (BE (err != REG_NOERROR, 0)) + return err; + } + } + } + + /* If the RE accepts NULL string. */ + if (BE (cur_state->halt, 0)) + { + if (!cur_state->has_constraint + || check_halt_state_context (mctx, cur_state, cur_str_idx)) + { + if (!fl_longest_match) + return cur_str_idx; + else + { + match_last = cur_str_idx; + match = 1; + } + } + } + + while (!re_string_eoi (&mctx->input)) + { + re_dfastate_t *old_state = cur_state; + Idx next_char_idx = re_string_cur_idx (&mctx->input) + 1; + + if (BE (next_char_idx >= mctx->input.bufs_len, 0) + || (BE (next_char_idx >= mctx->input.valid_len, 0) + && mctx->input.valid_len < mctx->input.len)) + { + err = extend_buffers (mctx); + if (BE (err != REG_NOERROR, 0)) + { + assert (err == REG_ESPACE); + return REG_ERROR; + } + } + + cur_state = transit_state (&err, mctx, cur_state); + if (mctx->state_log != NULL) + cur_state = merge_state_with_log (&err, mctx, cur_state); + + if (cur_state == NULL) + { + /* Reached the invalid state or an error. Try to recover a valid + state using the state log, if available and if we have not + already found a valid (even if not the longest) match. */ + if (BE (err != REG_NOERROR, 0)) + return REG_ERROR; + + if (mctx->state_log == NULL + || (match && !fl_longest_match) + || (cur_state = find_recover_state (&err, mctx)) == NULL) + break; + } + + if (BE (at_init_state, 0)) + { + if (old_state == cur_state) + next_start_idx = next_char_idx; + else + at_init_state = false; + } + + if (cur_state->halt) + { + /* Reached a halt state. + Check the halt state can satisfy the current context. */ + if (!cur_state->has_constraint + || check_halt_state_context (mctx, cur_state, + re_string_cur_idx (&mctx->input))) + { + /* We found an appropriate halt state. */ + match_last = re_string_cur_idx (&mctx->input); + match = 1; + + /* We found a match, do not modify match_first below. */ + p_match_first = NULL; + if (!fl_longest_match) + break; + } + } + } + + if (p_match_first) + *p_match_first += next_start_idx; + + return match_last; +} + +/* Check NODE match the current context. */ + +static bool +internal_function +check_halt_node_context (const re_dfa_t *dfa, Idx node, unsigned int context) +{ + re_token_type_t type = dfa->nodes[node].type; + unsigned int constraint = dfa->nodes[node].constraint; + if (type != END_OF_RE) + return false; + if (!constraint) + return true; + if (NOT_SATISFY_NEXT_CONSTRAINT (constraint, context)) + return false; + return true; +} + +/* Check the halt state STATE match the current context. + Return 0 if not match, if the node, STATE has, is a halt node and + match the context, return the node. */ + +static Idx +internal_function +check_halt_state_context (const re_match_context_t *mctx, + const re_dfastate_t *state, Idx idx) +{ + Idx i; + unsigned int context; +#ifdef DEBUG + assert (state->halt); +#endif + context = re_string_context_at (&mctx->input, idx, mctx->eflags); + for (i = 0; i < state->nodes.nelem; ++i) + if (check_halt_node_context (mctx->dfa, state->nodes.elems[i], context)) + return state->nodes.elems[i]; + return 0; +} + +/* Compute the next node to which "NFA" transit from NODE("NFA" is a NFA + corresponding to the DFA). + Return the destination node, and update EPS_VIA_NODES; + return REG_MISSING in case of errors. */ + +static Idx +internal_function +proceed_next_node (const re_match_context_t *mctx, Idx nregs, regmatch_t *regs, + Idx *pidx, Idx node, re_node_set *eps_via_nodes, + struct re_fail_stack_t *fs) +{ + const re_dfa_t *const dfa = mctx->dfa; + Idx i; + bool ok; + if (IS_EPSILON_NODE (dfa->nodes[node].type)) + { + re_node_set *cur_nodes = &mctx->state_log[*pidx]->nodes; + re_node_set *edests = &dfa->edests[node]; + Idx dest_node; + ok = re_node_set_insert (eps_via_nodes, node); + if (BE (! ok, 0)) + return REG_ERROR; + /* Pick up a valid destination, or return REG_MISSING if none + is found. */ + for (dest_node = REG_MISSING, i = 0; i < edests->nelem; ++i) + { + Idx candidate = edests->elems[i]; + if (!re_node_set_contains (cur_nodes, candidate)) + continue; + if (dest_node == REG_MISSING) + dest_node = candidate; + + else + { + /* In order to avoid infinite loop like "(a*)*", return the second + epsilon-transition if the first was already considered. */ + if (re_node_set_contains (eps_via_nodes, dest_node)) + return candidate; + + /* Otherwise, push the second epsilon-transition on the fail stack. */ + else if (fs != NULL + && push_fail_stack (fs, *pidx, candidate, nregs, regs, + eps_via_nodes)) + return REG_ERROR; + + /* We know we are going to exit. */ + break; + } + } + return dest_node; + } + else + { + Idx naccepted = 0; + re_token_type_t type = dfa->nodes[node].type; + +#ifdef RE_ENABLE_I18N + if (dfa->nodes[node].accept_mb) + naccepted = check_node_accept_bytes (dfa, node, &mctx->input, *pidx); + else +#endif /* RE_ENABLE_I18N */ + if (type == OP_BACK_REF) + { + Idx subexp_idx = dfa->nodes[node].opr.idx + 1; + naccepted = regs[subexp_idx].rm_eo - regs[subexp_idx].rm_so; + if (fs != NULL) + { + if (regs[subexp_idx].rm_so == -1 || regs[subexp_idx].rm_eo == -1) + return REG_MISSING; + else if (naccepted) + { + char *buf = (char *) re_string_get_buffer (&mctx->input); + if (memcmp (buf + regs[subexp_idx].rm_so, buf + *pidx, + naccepted) != 0) + return REG_MISSING; + } + } + + if (naccepted == 0) + { + Idx dest_node; + ok = re_node_set_insert (eps_via_nodes, node); + if (BE (! ok, 0)) + return REG_ERROR; + dest_node = dfa->edests[node].elems[0]; + if (re_node_set_contains (&mctx->state_log[*pidx]->nodes, + dest_node)) + return dest_node; + } + } + + if (naccepted != 0 + || check_node_accept (mctx, dfa->nodes + node, *pidx)) + { + Idx dest_node = dfa->nexts[node]; + *pidx = (naccepted == 0) ? *pidx + 1 : *pidx + naccepted; + if (fs && (*pidx > mctx->match_last || mctx->state_log[*pidx] == NULL + || !re_node_set_contains (&mctx->state_log[*pidx]->nodes, + dest_node))) + return REG_MISSING; + re_node_set_empty (eps_via_nodes); + return dest_node; + } + } + return REG_MISSING; +} + +static reg_errcode_t +internal_function +push_fail_stack (struct re_fail_stack_t *fs, Idx str_idx, Idx dest_node, + Idx nregs, regmatch_t *regs, re_node_set *eps_via_nodes) +{ + reg_errcode_t err; + Idx num = fs->num++; + if (fs->num == fs->alloc) + { + struct re_fail_stack_ent_t *new_array; + new_array = realloc (fs->stack, (sizeof (struct re_fail_stack_ent_t) + * fs->alloc * 2)); + if (new_array == NULL) + return REG_ESPACE; + fs->alloc *= 2; + fs->stack = new_array; + } + fs->stack[num].idx = str_idx; + fs->stack[num].node = dest_node; + fs->stack[num].regs = re_malloc (regmatch_t, nregs); + if (fs->stack[num].regs == NULL) + return REG_ESPACE; + memcpy (fs->stack[num].regs, regs, sizeof (regmatch_t) * nregs); + err = re_node_set_init_copy (&fs->stack[num].eps_via_nodes, eps_via_nodes); + return err; +} + +static Idx +internal_function +pop_fail_stack (struct re_fail_stack_t *fs, Idx *pidx, Idx nregs, + regmatch_t *regs, re_node_set *eps_via_nodes) +{ + Idx num = --fs->num; + assert (REG_VALID_INDEX (num)); + *pidx = fs->stack[num].idx; + memcpy (regs, fs->stack[num].regs, sizeof (regmatch_t) * nregs); + re_node_set_free (eps_via_nodes); + re_free (fs->stack[num].regs); + *eps_via_nodes = fs->stack[num].eps_via_nodes; + return fs->stack[num].node; +} + +/* Set the positions where the subexpressions are starts/ends to registers + PMATCH. + Note: We assume that pmatch[0] is already set, and + pmatch[i].rm_so == pmatch[i].rm_eo == -1 for 0 < i < nmatch. */ + +static reg_errcode_t +internal_function +set_regs (const regex_t *preg, const re_match_context_t *mctx, size_t nmatch, + regmatch_t *pmatch, bool fl_backtrack) +{ + const re_dfa_t *dfa = (const re_dfa_t *) preg->buffer; + Idx idx, cur_node; + re_node_set eps_via_nodes; + struct re_fail_stack_t *fs; + struct re_fail_stack_t fs_body = { 0, 2, NULL }; + regmatch_t *prev_idx_match; + bool prev_idx_match_malloced = false; + +#ifdef DEBUG + assert (nmatch > 1); + assert (mctx->state_log != NULL); +#endif + if (fl_backtrack) + { + fs = &fs_body; + fs->stack = re_malloc (struct re_fail_stack_ent_t, fs->alloc); + if (fs->stack == NULL) + return REG_ESPACE; + } + else + fs = NULL; + + cur_node = dfa->init_node; + re_node_set_init_empty (&eps_via_nodes); + + if (__libc_use_alloca (nmatch * sizeof (regmatch_t))) + prev_idx_match = (regmatch_t *) alloca (nmatch * sizeof (regmatch_t)); + else + { + prev_idx_match = re_malloc (regmatch_t, nmatch); + if (prev_idx_match == NULL) + { + free_fail_stack_return (fs); + return REG_ESPACE; + } + prev_idx_match_malloced = true; + } + memcpy (prev_idx_match, pmatch, sizeof (regmatch_t) * nmatch); + + for (idx = pmatch[0].rm_so; idx <= pmatch[0].rm_eo ;) + { + update_regs (dfa, pmatch, prev_idx_match, cur_node, idx, nmatch); + + if (idx == pmatch[0].rm_eo && cur_node == mctx->last_node) + { + Idx reg_idx; + if (fs) + { + for (reg_idx = 0; reg_idx < nmatch; ++reg_idx) + if (pmatch[reg_idx].rm_so > -1 && pmatch[reg_idx].rm_eo == -1) + break; + if (reg_idx == nmatch) + { + re_node_set_free (&eps_via_nodes); + if (prev_idx_match_malloced) + re_free (prev_idx_match); + return free_fail_stack_return (fs); + } + cur_node = pop_fail_stack (fs, &idx, nmatch, pmatch, + &eps_via_nodes); + } + else + { + re_node_set_free (&eps_via_nodes); + if (prev_idx_match_malloced) + re_free (prev_idx_match); + return REG_NOERROR; + } + } + + /* Proceed to next node. */ + cur_node = proceed_next_node (mctx, nmatch, pmatch, &idx, cur_node, + &eps_via_nodes, fs); + + if (BE (! REG_VALID_INDEX (cur_node), 0)) + { + if (BE (cur_node == REG_ERROR, 0)) + { + re_node_set_free (&eps_via_nodes); + if (prev_idx_match_malloced) + re_free (prev_idx_match); + free_fail_stack_return (fs); + return REG_ESPACE; + } + if (fs) + cur_node = pop_fail_stack (fs, &idx, nmatch, pmatch, + &eps_via_nodes); + else + { + re_node_set_free (&eps_via_nodes); + if (prev_idx_match_malloced) + re_free (prev_idx_match); + return REG_NOMATCH; + } + } + } + re_node_set_free (&eps_via_nodes); + if (prev_idx_match_malloced) + re_free (prev_idx_match); + return free_fail_stack_return (fs); +} + +static reg_errcode_t +internal_function +free_fail_stack_return (struct re_fail_stack_t *fs) +{ + if (fs) + { + Idx fs_idx; + for (fs_idx = 0; fs_idx < fs->num; ++fs_idx) + { + re_node_set_free (&fs->stack[fs_idx].eps_via_nodes); + re_free (fs->stack[fs_idx].regs); + } + re_free (fs->stack); + } + return REG_NOERROR; +} + +static void +internal_function +update_regs (const re_dfa_t *dfa, regmatch_t *pmatch, + regmatch_t *prev_idx_match, Idx cur_node, Idx cur_idx, Idx nmatch) +{ + int type = dfa->nodes[cur_node].type; + if (type == OP_OPEN_SUBEXP) + { + Idx reg_num = dfa->nodes[cur_node].opr.idx + 1; + + /* We are at the first node of this sub expression. */ + if (reg_num < nmatch) + { + pmatch[reg_num].rm_so = cur_idx; + pmatch[reg_num].rm_eo = -1; + } + } + else if (type == OP_CLOSE_SUBEXP) + { + Idx reg_num = dfa->nodes[cur_node].opr.idx + 1; + if (reg_num < nmatch) + { + /* We are at the last node of this sub expression. */ + if (pmatch[reg_num].rm_so < cur_idx) + { + pmatch[reg_num].rm_eo = cur_idx; + /* This is a non-empty match or we are not inside an optional + subexpression. Accept this right away. */ + memcpy (prev_idx_match, pmatch, sizeof (regmatch_t) * nmatch); + } + else + { + if (dfa->nodes[cur_node].opt_subexp + && prev_idx_match[reg_num].rm_so != -1) + /* We transited through an empty match for an optional + subexpression, like (a?)*, and this is not the subexp's + first match. Copy back the old content of the registers + so that matches of an inner subexpression are undone as + well, like in ((a?))*. */ + memcpy (pmatch, prev_idx_match, sizeof (regmatch_t) * nmatch); + else + /* We completed a subexpression, but it may be part of + an optional one, so do not update PREV_IDX_MATCH. */ + pmatch[reg_num].rm_eo = cur_idx; + } + } + } +} + +/* This function checks the STATE_LOG from the SCTX->last_str_idx to 0 + and sift the nodes in each states according to the following rules. + Updated state_log will be wrote to STATE_LOG. + + Rules: We throw away the Node `a' in the STATE_LOG[STR_IDX] if... + 1. When STR_IDX == MATCH_LAST(the last index in the state_log): + If `a' isn't the LAST_NODE and `a' can't epsilon transit to + the LAST_NODE, we throw away the node `a'. + 2. When 0 <= STR_IDX < MATCH_LAST and `a' accepts + string `s' and transit to `b': + i. If 'b' isn't in the STATE_LOG[STR_IDX+strlen('s')], we throw + away the node `a'. + ii. If 'b' is in the STATE_LOG[STR_IDX+strlen('s')] but 'b' is + thrown away, we throw away the node `a'. + 3. When 0 <= STR_IDX < MATCH_LAST and 'a' epsilon transit to 'b': + i. If 'b' isn't in the STATE_LOG[STR_IDX], we throw away the + node `a'. + ii. If 'b' is in the STATE_LOG[STR_IDX] but 'b' is thrown away, + we throw away the node `a'. */ + +#define STATE_NODE_CONTAINS(state,node) \ + ((state) != NULL && re_node_set_contains (&(state)->nodes, node)) + +static reg_errcode_t +internal_function +sift_states_backward (const re_match_context_t *mctx, re_sift_context_t *sctx) +{ + reg_errcode_t err; + int null_cnt = 0; + Idx str_idx = sctx->last_str_idx; + re_node_set cur_dest; + +#ifdef DEBUG + assert (mctx->state_log != NULL && mctx->state_log[str_idx] != NULL); +#endif + + /* Build sifted state_log[str_idx]. It has the nodes which can epsilon + transit to the last_node and the last_node itself. */ + err = re_node_set_init_1 (&cur_dest, sctx->last_node); + if (BE (err != REG_NOERROR, 0)) + return err; + err = update_cur_sifted_state (mctx, sctx, str_idx, &cur_dest); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + + /* Then check each states in the state_log. */ + while (str_idx > 0) + { + /* Update counters. */ + null_cnt = (sctx->sifted_states[str_idx] == NULL) ? null_cnt + 1 : 0; + if (null_cnt > mctx->max_mb_elem_len) + { + memset (sctx->sifted_states, '\0', + sizeof (re_dfastate_t *) * str_idx); + re_node_set_free (&cur_dest); + return REG_NOERROR; + } + re_node_set_empty (&cur_dest); + --str_idx; + + if (mctx->state_log[str_idx]) + { + err = build_sifted_states (mctx, sctx, str_idx, &cur_dest); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + } + + /* Add all the nodes which satisfy the following conditions: + - It can epsilon transit to a node in CUR_DEST. + - It is in CUR_SRC. + And update state_log. */ + err = update_cur_sifted_state (mctx, sctx, str_idx, &cur_dest); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + } + err = REG_NOERROR; + free_return: + re_node_set_free (&cur_dest); + return err; +} + +static reg_errcode_t +internal_function +build_sifted_states (const re_match_context_t *mctx, re_sift_context_t *sctx, + Idx str_idx, re_node_set *cur_dest) +{ + const re_dfa_t *const dfa = mctx->dfa; + const re_node_set *cur_src = &mctx->state_log[str_idx]->non_eps_nodes; + Idx i; + + /* Then build the next sifted state. + We build the next sifted state on `cur_dest', and update + `sifted_states[str_idx]' with `cur_dest'. + Note: + `cur_dest' is the sifted state from `state_log[str_idx + 1]'. + `cur_src' points the node_set of the old `state_log[str_idx]' + (with the epsilon nodes pre-filtered out). */ + for (i = 0; i < cur_src->nelem; i++) + { + Idx prev_node = cur_src->elems[i]; + int naccepted = 0; + bool ok; + +#ifdef DEBUG + re_token_type_t type = dfa->nodes[prev_node].type; + assert (!IS_EPSILON_NODE (type)); +#endif +#ifdef RE_ENABLE_I18N + /* If the node may accept `multi byte'. */ + if (dfa->nodes[prev_node].accept_mb) + naccepted = sift_states_iter_mb (mctx, sctx, prev_node, + str_idx, sctx->last_str_idx); +#endif /* RE_ENABLE_I18N */ + + /* We don't check backreferences here. + See update_cur_sifted_state(). */ + if (!naccepted + && check_node_accept (mctx, dfa->nodes + prev_node, str_idx) + && STATE_NODE_CONTAINS (sctx->sifted_states[str_idx + 1], + dfa->nexts[prev_node])) + naccepted = 1; + + if (naccepted == 0) + continue; + + if (sctx->limits.nelem) + { + Idx to_idx = str_idx + naccepted; + if (check_dst_limits (mctx, &sctx->limits, + dfa->nexts[prev_node], to_idx, + prev_node, str_idx)) + continue; + } + ok = re_node_set_insert (cur_dest, prev_node); + if (BE (! ok, 0)) + return REG_ESPACE; + } + + return REG_NOERROR; +} + +/* Helper functions. */ + +static reg_errcode_t +internal_function +clean_state_log_if_needed (re_match_context_t *mctx, Idx next_state_log_idx) +{ + Idx top = mctx->state_log_top; + + if (next_state_log_idx >= mctx->input.bufs_len + || (next_state_log_idx >= mctx->input.valid_len + && mctx->input.valid_len < mctx->input.len)) + { + reg_errcode_t err; + err = extend_buffers (mctx); + if (BE (err != REG_NOERROR, 0)) + return err; + } + + if (top < next_state_log_idx) + { + memset (mctx->state_log + top + 1, '\0', + sizeof (re_dfastate_t *) * (next_state_log_idx - top)); + mctx->state_log_top = next_state_log_idx; + } + return REG_NOERROR; +} + +static reg_errcode_t +internal_function +merge_state_array (const re_dfa_t *dfa, re_dfastate_t **dst, + re_dfastate_t **src, Idx num) +{ + Idx st_idx; + reg_errcode_t err; + for (st_idx = 0; st_idx < num; ++st_idx) + { + if (dst[st_idx] == NULL) + dst[st_idx] = src[st_idx]; + else if (src[st_idx] != NULL) + { + re_node_set merged_set; + err = re_node_set_init_union (&merged_set, &dst[st_idx]->nodes, + &src[st_idx]->nodes); + if (BE (err != REG_NOERROR, 0)) + return err; + dst[st_idx] = re_acquire_state (&err, dfa, &merged_set); + re_node_set_free (&merged_set); + if (BE (err != REG_NOERROR, 0)) + return err; + } + } + return REG_NOERROR; +} + +static reg_errcode_t +internal_function +update_cur_sifted_state (const re_match_context_t *mctx, + re_sift_context_t *sctx, Idx str_idx, + re_node_set *dest_nodes) +{ + const re_dfa_t *const dfa = mctx->dfa; + reg_errcode_t err = REG_NOERROR; + const re_node_set *candidates; + candidates = ((mctx->state_log[str_idx] == NULL) ? NULL + : &mctx->state_log[str_idx]->nodes); + + if (dest_nodes->nelem == 0) + sctx->sifted_states[str_idx] = NULL; + else + { + if (candidates) + { + /* At first, add the nodes which can epsilon transit to a node in + DEST_NODE. */ + err = add_epsilon_src_nodes (dfa, dest_nodes, candidates); + if (BE (err != REG_NOERROR, 0)) + return err; + + /* Then, check the limitations in the current sift_context. */ + if (sctx->limits.nelem) + { + err = check_subexp_limits (dfa, dest_nodes, candidates, &sctx->limits, + mctx->bkref_ents, str_idx); + if (BE (err != REG_NOERROR, 0)) + return err; + } + } + + sctx->sifted_states[str_idx] = re_acquire_state (&err, dfa, dest_nodes); + if (BE (err != REG_NOERROR, 0)) + return err; + } + + if (candidates && mctx->state_log[str_idx]->has_backref) + { + err = sift_states_bkref (mctx, sctx, str_idx, candidates); + if (BE (err != REG_NOERROR, 0)) + return err; + } + return REG_NOERROR; +} + +static reg_errcode_t +internal_function +add_epsilon_src_nodes (const re_dfa_t *dfa, re_node_set *dest_nodes, + const re_node_set *candidates) +{ + reg_errcode_t err = REG_NOERROR; + Idx i; + + re_dfastate_t *state = re_acquire_state (&err, dfa, dest_nodes); + if (BE (err != REG_NOERROR, 0)) + return err; + + if (!state->inveclosure.alloc) + { + err = re_node_set_alloc (&state->inveclosure, dest_nodes->nelem); + if (BE (err != REG_NOERROR, 0)) + return REG_ESPACE; + for (i = 0; i < dest_nodes->nelem; i++) + re_node_set_merge (&state->inveclosure, + dfa->inveclosures + dest_nodes->elems[i]); + } + return re_node_set_add_intersect (dest_nodes, candidates, + &state->inveclosure); +} + +static reg_errcode_t +internal_function +sub_epsilon_src_nodes (const re_dfa_t *dfa, Idx node, re_node_set *dest_nodes, + const re_node_set *candidates) +{ + Idx ecl_idx; + reg_errcode_t err; + re_node_set *inv_eclosure = dfa->inveclosures + node; + re_node_set except_nodes; + re_node_set_init_empty (&except_nodes); + for (ecl_idx = 0; ecl_idx < inv_eclosure->nelem; ++ecl_idx) + { + Idx cur_node = inv_eclosure->elems[ecl_idx]; + if (cur_node == node) + continue; + if (IS_EPSILON_NODE (dfa->nodes[cur_node].type)) + { + Idx edst1 = dfa->edests[cur_node].elems[0]; + Idx edst2 = ((dfa->edests[cur_node].nelem > 1) + ? dfa->edests[cur_node].elems[1] : REG_MISSING); + if ((!re_node_set_contains (inv_eclosure, edst1) + && re_node_set_contains (dest_nodes, edst1)) + || (REG_VALID_NONZERO_INDEX (edst2) + && !re_node_set_contains (inv_eclosure, edst2) + && re_node_set_contains (dest_nodes, edst2))) + { + err = re_node_set_add_intersect (&except_nodes, candidates, + dfa->inveclosures + cur_node); + if (BE (err != REG_NOERROR, 0)) + { + re_node_set_free (&except_nodes); + return err; + } + } + } + } + for (ecl_idx = 0; ecl_idx < inv_eclosure->nelem; ++ecl_idx) + { + Idx cur_node = inv_eclosure->elems[ecl_idx]; + if (!re_node_set_contains (&except_nodes, cur_node)) + { + Idx idx = re_node_set_contains (dest_nodes, cur_node) - 1; + re_node_set_remove_at (dest_nodes, idx); + } + } + re_node_set_free (&except_nodes); + return REG_NOERROR; +} + +static bool +internal_function +check_dst_limits (const re_match_context_t *mctx, const re_node_set *limits, + Idx dst_node, Idx dst_idx, Idx src_node, Idx src_idx) +{ + const re_dfa_t *const dfa = mctx->dfa; + Idx lim_idx, src_pos, dst_pos; + + Idx dst_bkref_idx = search_cur_bkref_entry (mctx, dst_idx); + Idx src_bkref_idx = search_cur_bkref_entry (mctx, src_idx); + for (lim_idx = 0; lim_idx < limits->nelem; ++lim_idx) + { + Idx subexp_idx; + struct re_backref_cache_entry *ent; + ent = mctx->bkref_ents + limits->elems[lim_idx]; + subexp_idx = dfa->nodes[ent->node].opr.idx; + + dst_pos = check_dst_limits_calc_pos (mctx, limits->elems[lim_idx], + subexp_idx, dst_node, dst_idx, + dst_bkref_idx); + src_pos = check_dst_limits_calc_pos (mctx, limits->elems[lim_idx], + subexp_idx, src_node, src_idx, + src_bkref_idx); + + /* In case of: + ( ) + ( ) + ( ) */ + if (src_pos == dst_pos) + continue; /* This is unrelated limitation. */ + else + return true; + } + return false; +} + +static int +internal_function +check_dst_limits_calc_pos_1 (const re_match_context_t *mctx, int boundaries, + Idx subexp_idx, Idx from_node, Idx bkref_idx) +{ + const re_dfa_t *const dfa = mctx->dfa; + const re_node_set *eclosures = dfa->eclosures + from_node; + Idx node_idx; + + /* Else, we are on the boundary: examine the nodes on the epsilon + closure. */ + for (node_idx = 0; node_idx < eclosures->nelem; ++node_idx) + { + Idx node = eclosures->elems[node_idx]; + switch (dfa->nodes[node].type) + { + case OP_BACK_REF: + if (bkref_idx != REG_MISSING) + { + struct re_backref_cache_entry *ent = mctx->bkref_ents + bkref_idx; + do + { + Idx dst; + int cpos; + + if (ent->node != node) + continue; + + if (subexp_idx < BITSET_WORD_BITS + && !(ent->eps_reachable_subexps_map + & ((bitset_word_t) 1 << subexp_idx))) + continue; + + /* Recurse trying to reach the OP_OPEN_SUBEXP and + OP_CLOSE_SUBEXP cases below. But, if the + destination node is the same node as the source + node, don't recurse because it would cause an + infinite loop: a regex that exhibits this behavior + is ()\1*\1* */ + dst = dfa->edests[node].elems[0]; + if (dst == from_node) + { + if (boundaries & 1) + return -1; + else /* if (boundaries & 2) */ + return 0; + } + + cpos = + check_dst_limits_calc_pos_1 (mctx, boundaries, subexp_idx, + dst, bkref_idx); + if (cpos == -1 /* && (boundaries & 1) */) + return -1; + if (cpos == 0 && (boundaries & 2)) + return 0; + + if (subexp_idx < BITSET_WORD_BITS) + ent->eps_reachable_subexps_map + &= ~((bitset_word_t) 1 << subexp_idx); + } + while (ent++->more); + } + break; + + case OP_OPEN_SUBEXP: + if ((boundaries & 1) && subexp_idx == dfa->nodes[node].opr.idx) + return -1; + break; + + case OP_CLOSE_SUBEXP: + if ((boundaries & 2) && subexp_idx == dfa->nodes[node].opr.idx) + return 0; + break; + + default: + break; + } + } + + return (boundaries & 2) ? 1 : 0; +} + +static int +internal_function +check_dst_limits_calc_pos (const re_match_context_t *mctx, Idx limit, + Idx subexp_idx, Idx from_node, Idx str_idx, + Idx bkref_idx) +{ + struct re_backref_cache_entry *lim = mctx->bkref_ents + limit; + int boundaries; + + /* If we are outside the range of the subexpression, return -1 or 1. */ + if (str_idx < lim->subexp_from) + return -1; + + if (lim->subexp_to < str_idx) + return 1; + + /* If we are within the subexpression, return 0. */ + boundaries = (str_idx == lim->subexp_from); + boundaries |= (str_idx == lim->subexp_to) << 1; + if (boundaries == 0) + return 0; + + /* Else, examine epsilon closure. */ + return check_dst_limits_calc_pos_1 (mctx, boundaries, subexp_idx, + from_node, bkref_idx); +} + +/* Check the limitations of sub expressions LIMITS, and remove the nodes + which are against limitations from DEST_NODES. */ + +static reg_errcode_t +internal_function +check_subexp_limits (const re_dfa_t *dfa, re_node_set *dest_nodes, + const re_node_set *candidates, re_node_set *limits, + struct re_backref_cache_entry *bkref_ents, Idx str_idx) +{ + reg_errcode_t err; + Idx node_idx, lim_idx; + + for (lim_idx = 0; lim_idx < limits->nelem; ++lim_idx) + { + Idx subexp_idx; + struct re_backref_cache_entry *ent; + ent = bkref_ents + limits->elems[lim_idx]; + + if (str_idx <= ent->subexp_from || ent->str_idx < str_idx) + continue; /* This is unrelated limitation. */ + + subexp_idx = dfa->nodes[ent->node].opr.idx; + if (ent->subexp_to == str_idx) + { + Idx ops_node = REG_MISSING; + Idx cls_node = REG_MISSING; + for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx) + { + Idx node = dest_nodes->elems[node_idx]; + re_token_type_t type = dfa->nodes[node].type; + if (type == OP_OPEN_SUBEXP + && subexp_idx == dfa->nodes[node].opr.idx) + ops_node = node; + else if (type == OP_CLOSE_SUBEXP + && subexp_idx == dfa->nodes[node].opr.idx) + cls_node = node; + } + + /* Check the limitation of the open subexpression. */ + /* Note that (ent->subexp_to = str_idx != ent->subexp_from). */ + if (REG_VALID_INDEX (ops_node)) + { + err = sub_epsilon_src_nodes (dfa, ops_node, dest_nodes, + candidates); + if (BE (err != REG_NOERROR, 0)) + return err; + } + + /* Check the limitation of the close subexpression. */ + if (REG_VALID_INDEX (cls_node)) + for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx) + { + Idx node = dest_nodes->elems[node_idx]; + if (!re_node_set_contains (dfa->inveclosures + node, + cls_node) + && !re_node_set_contains (dfa->eclosures + node, + cls_node)) + { + /* It is against this limitation. + Remove it form the current sifted state. */ + err = sub_epsilon_src_nodes (dfa, node, dest_nodes, + candidates); + if (BE (err != REG_NOERROR, 0)) + return err; + --node_idx; + } + } + } + else /* (ent->subexp_to != str_idx) */ + { + for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx) + { + Idx node = dest_nodes->elems[node_idx]; + re_token_type_t type = dfa->nodes[node].type; + if (type == OP_CLOSE_SUBEXP || type == OP_OPEN_SUBEXP) + { + if (subexp_idx != dfa->nodes[node].opr.idx) + continue; + /* It is against this limitation. + Remove it form the current sifted state. */ + err = sub_epsilon_src_nodes (dfa, node, dest_nodes, + candidates); + if (BE (err != REG_NOERROR, 0)) + return err; + } + } + } + } + return REG_NOERROR; +} + +static reg_errcode_t +internal_function +sift_states_bkref (const re_match_context_t *mctx, re_sift_context_t *sctx, + Idx str_idx, const re_node_set *candidates) +{ + const re_dfa_t *const dfa = mctx->dfa; + reg_errcode_t err; + Idx node_idx, node; + re_sift_context_t local_sctx; + Idx first_idx = search_cur_bkref_entry (mctx, str_idx); + + if (first_idx == REG_MISSING) + return REG_NOERROR; + + local_sctx.sifted_states = NULL; /* Mark that it hasn't been initialized. */ + + for (node_idx = 0; node_idx < candidates->nelem; ++node_idx) + { + Idx enabled_idx; + re_token_type_t type; + struct re_backref_cache_entry *entry; + node = candidates->elems[node_idx]; + type = dfa->nodes[node].type; + /* Avoid infinite loop for the REs like "()\1+". */ + if (node == sctx->last_node && str_idx == sctx->last_str_idx) + continue; + if (type != OP_BACK_REF) + continue; + + entry = mctx->bkref_ents + first_idx; + enabled_idx = first_idx; + do + { + Idx subexp_len; + Idx to_idx; + Idx dst_node; + bool ok; + re_dfastate_t *cur_state; + + if (entry->node != node) + continue; + subexp_len = entry->subexp_to - entry->subexp_from; + to_idx = str_idx + subexp_len; + dst_node = (subexp_len ? dfa->nexts[node] + : dfa->edests[node].elems[0]); + + if (to_idx > sctx->last_str_idx + || sctx->sifted_states[to_idx] == NULL + || !STATE_NODE_CONTAINS (sctx->sifted_states[to_idx], dst_node) + || check_dst_limits (mctx, &sctx->limits, node, + str_idx, dst_node, to_idx)) + continue; + + if (local_sctx.sifted_states == NULL) + { + local_sctx = *sctx; + err = re_node_set_init_copy (&local_sctx.limits, &sctx->limits); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + } + local_sctx.last_node = node; + local_sctx.last_str_idx = str_idx; + ok = re_node_set_insert (&local_sctx.limits, enabled_idx); + if (BE (! ok, 0)) + { + err = REG_ESPACE; + goto free_return; + } + cur_state = local_sctx.sifted_states[str_idx]; + err = sift_states_backward (mctx, &local_sctx); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + if (sctx->limited_states != NULL) + { + err = merge_state_array (dfa, sctx->limited_states, + local_sctx.sifted_states, + str_idx + 1); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + } + local_sctx.sifted_states[str_idx] = cur_state; + re_node_set_remove (&local_sctx.limits, enabled_idx); + + /* mctx->bkref_ents may have changed, reload the pointer. */ + entry = mctx->bkref_ents + enabled_idx; + } + while (enabled_idx++, entry++->more); + } + err = REG_NOERROR; + free_return: + if (local_sctx.sifted_states != NULL) + { + re_node_set_free (&local_sctx.limits); + } + + return err; +} + + +#ifdef RE_ENABLE_I18N +static int +internal_function +sift_states_iter_mb (const re_match_context_t *mctx, re_sift_context_t *sctx, + Idx node_idx, Idx str_idx, Idx max_str_idx) +{ + const re_dfa_t *const dfa = mctx->dfa; + int naccepted; + /* Check the node can accept `multi byte'. */ + naccepted = check_node_accept_bytes (dfa, node_idx, &mctx->input, str_idx); + if (naccepted > 0 && str_idx + naccepted <= max_str_idx && + !STATE_NODE_CONTAINS (sctx->sifted_states[str_idx + naccepted], + dfa->nexts[node_idx])) + /* The node can't accept the `multi byte', or the + destination was already thrown away, then the node + could't accept the current input `multi byte'. */ + naccepted = 0; + /* Otherwise, it is sure that the node could accept + `naccepted' bytes input. */ + return naccepted; +} +#endif /* RE_ENABLE_I18N */ + + +/* Functions for state transition. */ + +/* Return the next state to which the current state STATE will transit by + accepting the current input byte, and update STATE_LOG if necessary. + If STATE can accept a multibyte char/collating element/back reference + update the destination of STATE_LOG. */ + +static re_dfastate_t * +internal_function +transit_state (reg_errcode_t *err, re_match_context_t *mctx, + re_dfastate_t *state) +{ + re_dfastate_t **trtable; + unsigned char ch; + +#ifdef RE_ENABLE_I18N + /* If the current state can accept multibyte. */ + if (BE (state->accept_mb, 0)) + { + *err = transit_state_mb (mctx, state); + if (BE (*err != REG_NOERROR, 0)) + return NULL; + } +#endif /* RE_ENABLE_I18N */ + + /* Then decide the next state with the single byte. */ +#if 0 + if (0) + /* don't use transition table */ + return transit_state_sb (err, mctx, state); +#endif + + /* Use transition table */ + ch = re_string_fetch_byte (&mctx->input); + for (;;) + { + trtable = state->trtable; + if (BE (trtable != NULL, 1)) + return trtable[ch]; + + trtable = state->word_trtable; + if (BE (trtable != NULL, 1)) + { + unsigned int context; + context + = re_string_context_at (&mctx->input, + re_string_cur_idx (&mctx->input) - 1, + mctx->eflags); + if (IS_WORD_CONTEXT (context)) + return trtable[ch + SBC_MAX]; + else + return trtable[ch]; + } + + if (!build_trtable (mctx->dfa, state)) + { + *err = REG_ESPACE; + return NULL; + } + + /* Retry, we now have a transition table. */ + } +} + +/* Update the state_log if we need */ +static re_dfastate_t * +internal_function +merge_state_with_log (reg_errcode_t *err, re_match_context_t *mctx, + re_dfastate_t *next_state) +{ + const re_dfa_t *const dfa = mctx->dfa; + Idx cur_idx = re_string_cur_idx (&mctx->input); + + if (cur_idx > mctx->state_log_top) + { + mctx->state_log[cur_idx] = next_state; + mctx->state_log_top = cur_idx; + } + else if (mctx->state_log[cur_idx] == 0) + { + mctx->state_log[cur_idx] = next_state; + } + else + { + re_dfastate_t *pstate; + unsigned int context; + re_node_set next_nodes, *log_nodes, *table_nodes = NULL; + /* If (state_log[cur_idx] != 0), it implies that cur_idx is + the destination of a multibyte char/collating element/ + back reference. Then the next state is the union set of + these destinations and the results of the transition table. */ + pstate = mctx->state_log[cur_idx]; + log_nodes = pstate->entrance_nodes; + if (next_state != NULL) + { + table_nodes = next_state->entrance_nodes; + *err = re_node_set_init_union (&next_nodes, table_nodes, + log_nodes); + if (BE (*err != REG_NOERROR, 0)) + return NULL; + } + else + next_nodes = *log_nodes; + /* Note: We already add the nodes of the initial state, + then we don't need to add them here. */ + + context = re_string_context_at (&mctx->input, + re_string_cur_idx (&mctx->input) - 1, + mctx->eflags); + next_state = mctx->state_log[cur_idx] + = re_acquire_state_context (err, dfa, &next_nodes, context); + /* We don't need to check errors here, since the return value of + this function is next_state and ERR is already set. */ + + if (table_nodes != NULL) + re_node_set_free (&next_nodes); + } + + if (BE (dfa->nbackref, 0) && next_state != NULL) + { + /* Check OP_OPEN_SUBEXP in the current state in case that we use them + later. We must check them here, since the back references in the + next state might use them. */ + *err = check_subexp_matching_top (mctx, &next_state->nodes, + cur_idx); + if (BE (*err != REG_NOERROR, 0)) + return NULL; + + /* If the next state has back references. */ + if (next_state->has_backref) + { + *err = transit_state_bkref (mctx, &next_state->nodes); + if (BE (*err != REG_NOERROR, 0)) + return NULL; + next_state = mctx->state_log[cur_idx]; + } + } + + return next_state; +} + +/* Skip bytes in the input that correspond to part of a + multi-byte match, then look in the log for a state + from which to restart matching. */ +static re_dfastate_t * +internal_function +find_recover_state (reg_errcode_t *err, re_match_context_t *mctx) +{ + re_dfastate_t *cur_state; + do + { + Idx max = mctx->state_log_top; + Idx cur_str_idx = re_string_cur_idx (&mctx->input); + + do + { + if (++cur_str_idx > max) + return NULL; + re_string_skip_bytes (&mctx->input, 1); + } + while (mctx->state_log[cur_str_idx] == NULL); + + cur_state = merge_state_with_log (err, mctx, NULL); + } + while (*err == REG_NOERROR && cur_state == NULL); + return cur_state; +} + +/* Helper functions for transit_state. */ + +/* From the node set CUR_NODES, pick up the nodes whose types are + OP_OPEN_SUBEXP and which have corresponding back references in the regular + expression. And register them to use them later for evaluating the + correspoding back references. */ + +static reg_errcode_t +internal_function +check_subexp_matching_top (re_match_context_t *mctx, re_node_set *cur_nodes, + Idx str_idx) +{ + const re_dfa_t *const dfa = mctx->dfa; + Idx node_idx; + reg_errcode_t err; + + /* TODO: This isn't efficient. + Because there might be more than one nodes whose types are + OP_OPEN_SUBEXP and whose index is SUBEXP_IDX, we must check all + nodes. + E.g. RE: (a){2} */ + for (node_idx = 0; node_idx < cur_nodes->nelem; ++node_idx) + { + Idx node = cur_nodes->elems[node_idx]; + if (dfa->nodes[node].type == OP_OPEN_SUBEXP + && dfa->nodes[node].opr.idx < BITSET_WORD_BITS + && (dfa->used_bkref_map + & ((bitset_word_t) 1 << dfa->nodes[node].opr.idx))) + { + err = match_ctx_add_subtop (mctx, node, str_idx); + if (BE (err != REG_NOERROR, 0)) + return err; + } + } + return REG_NOERROR; +} + +#if 0 +/* Return the next state to which the current state STATE will transit by + accepting the current input byte. */ + +static re_dfastate_t * +transit_state_sb (reg_errcode_t *err, re_match_context_t *mctx, + re_dfastate_t *state) +{ + const re_dfa_t *const dfa = mctx->dfa; + re_node_set next_nodes; + re_dfastate_t *next_state; + Idx node_cnt, cur_str_idx = re_string_cur_idx (&mctx->input); + unsigned int context; + + *err = re_node_set_alloc (&next_nodes, state->nodes.nelem + 1); + if (BE (*err != REG_NOERROR, 0)) + return NULL; + for (node_cnt = 0; node_cnt < state->nodes.nelem; ++node_cnt) + { + Idx cur_node = state->nodes.elems[node_cnt]; + if (check_node_accept (mctx, dfa->nodes + cur_node, cur_str_idx)) + { + *err = re_node_set_merge (&next_nodes, + dfa->eclosures + dfa->nexts[cur_node]); + if (BE (*err != REG_NOERROR, 0)) + { + re_node_set_free (&next_nodes); + return NULL; + } + } + } + context = re_string_context_at (&mctx->input, cur_str_idx, mctx->eflags); + next_state = re_acquire_state_context (err, dfa, &next_nodes, context); + /* We don't need to check errors here, since the return value of + this function is next_state and ERR is already set. */ + + re_node_set_free (&next_nodes); + re_string_skip_bytes (&mctx->input, 1); + return next_state; +} +#endif + +#ifdef RE_ENABLE_I18N +static reg_errcode_t +internal_function +transit_state_mb (re_match_context_t *mctx, re_dfastate_t *pstate) +{ + const re_dfa_t *const dfa = mctx->dfa; + reg_errcode_t err; + Idx i; + + for (i = 0; i < pstate->nodes.nelem; ++i) + { + re_node_set dest_nodes, *new_nodes; + Idx cur_node_idx = pstate->nodes.elems[i]; + int naccepted; + Idx dest_idx; + unsigned int context; + re_dfastate_t *dest_state; + + if (!dfa->nodes[cur_node_idx].accept_mb) + continue; + + if (dfa->nodes[cur_node_idx].constraint) + { + context = re_string_context_at (&mctx->input, + re_string_cur_idx (&mctx->input), + mctx->eflags); + if (NOT_SATISFY_NEXT_CONSTRAINT (dfa->nodes[cur_node_idx].constraint, + context)) + continue; + } + + /* How many bytes the node can accept? */ + naccepted = check_node_accept_bytes (dfa, cur_node_idx, &mctx->input, + re_string_cur_idx (&mctx->input)); + if (naccepted == 0) + continue; + + /* The node can accepts `naccepted' bytes. */ + dest_idx = re_string_cur_idx (&mctx->input) + naccepted; + mctx->max_mb_elem_len = ((mctx->max_mb_elem_len < naccepted) ? naccepted + : mctx->max_mb_elem_len); + err = clean_state_log_if_needed (mctx, dest_idx); + if (BE (err != REG_NOERROR, 0)) + return err; +#ifdef DEBUG + assert (dfa->nexts[cur_node_idx] != REG_MISSING); +#endif + new_nodes = dfa->eclosures + dfa->nexts[cur_node_idx]; + + dest_state = mctx->state_log[dest_idx]; + if (dest_state == NULL) + dest_nodes = *new_nodes; + else + { + err = re_node_set_init_union (&dest_nodes, + dest_state->entrance_nodes, new_nodes); + if (BE (err != REG_NOERROR, 0)) + return err; + } + context = re_string_context_at (&mctx->input, dest_idx - 1, + mctx->eflags); + mctx->state_log[dest_idx] + = re_acquire_state_context (&err, dfa, &dest_nodes, context); + if (dest_state != NULL) + re_node_set_free (&dest_nodes); + if (BE (mctx->state_log[dest_idx] == NULL && err != REG_NOERROR, 0)) + return err; + } + return REG_NOERROR; +} +#endif /* RE_ENABLE_I18N */ + +static reg_errcode_t +internal_function +transit_state_bkref (re_match_context_t *mctx, const re_node_set *nodes) +{ + const re_dfa_t *const dfa = mctx->dfa; + reg_errcode_t err; + Idx i; + Idx cur_str_idx = re_string_cur_idx (&mctx->input); + + for (i = 0; i < nodes->nelem; ++i) + { + Idx dest_str_idx, prev_nelem, bkc_idx; + Idx node_idx = nodes->elems[i]; + unsigned int context; + const re_token_t *node = dfa->nodes + node_idx; + re_node_set *new_dest_nodes; + + /* Check whether `node' is a backreference or not. */ + if (node->type != OP_BACK_REF) + continue; + + if (node->constraint) + { + context = re_string_context_at (&mctx->input, cur_str_idx, + mctx->eflags); + if (NOT_SATISFY_NEXT_CONSTRAINT (node->constraint, context)) + continue; + } + + /* `node' is a backreference. + Check the substring which the substring matched. */ + bkc_idx = mctx->nbkref_ents; + err = get_subexp (mctx, node_idx, cur_str_idx); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + + /* And add the epsilon closures (which is `new_dest_nodes') of + the backreference to appropriate state_log. */ +#ifdef DEBUG + assert (dfa->nexts[node_idx] != REG_MISSING); +#endif + for (; bkc_idx < mctx->nbkref_ents; ++bkc_idx) + { + Idx subexp_len; + re_dfastate_t *dest_state; + struct re_backref_cache_entry *bkref_ent; + bkref_ent = mctx->bkref_ents + bkc_idx; + if (bkref_ent->node != node_idx || bkref_ent->str_idx != cur_str_idx) + continue; + subexp_len = bkref_ent->subexp_to - bkref_ent->subexp_from; + new_dest_nodes = (subexp_len == 0 + ? dfa->eclosures + dfa->edests[node_idx].elems[0] + : dfa->eclosures + dfa->nexts[node_idx]); + dest_str_idx = (cur_str_idx + bkref_ent->subexp_to + - bkref_ent->subexp_from); + context = re_string_context_at (&mctx->input, dest_str_idx - 1, + mctx->eflags); + dest_state = mctx->state_log[dest_str_idx]; + prev_nelem = ((mctx->state_log[cur_str_idx] == NULL) ? 0 + : mctx->state_log[cur_str_idx]->nodes.nelem); + /* Add `new_dest_node' to state_log. */ + if (dest_state == NULL) + { + mctx->state_log[dest_str_idx] + = re_acquire_state_context (&err, dfa, new_dest_nodes, + context); + if (BE (mctx->state_log[dest_str_idx] == NULL + && err != REG_NOERROR, 0)) + goto free_return; + } + else + { + re_node_set dest_nodes; + err = re_node_set_init_union (&dest_nodes, + dest_state->entrance_nodes, + new_dest_nodes); + if (BE (err != REG_NOERROR, 0)) + { + re_node_set_free (&dest_nodes); + goto free_return; + } + mctx->state_log[dest_str_idx] + = re_acquire_state_context (&err, dfa, &dest_nodes, context); + re_node_set_free (&dest_nodes); + if (BE (mctx->state_log[dest_str_idx] == NULL + && err != REG_NOERROR, 0)) + goto free_return; + } + /* We need to check recursively if the backreference can epsilon + transit. */ + if (subexp_len == 0 + && mctx->state_log[cur_str_idx]->nodes.nelem > prev_nelem) + { + err = check_subexp_matching_top (mctx, new_dest_nodes, + cur_str_idx); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + err = transit_state_bkref (mctx, new_dest_nodes); + if (BE (err != REG_NOERROR, 0)) + goto free_return; + } + } + } + err = REG_NOERROR; + free_return: + return err; +} + +/* Enumerate all the candidates which the backreference BKREF_NODE can match + at BKREF_STR_IDX, and register them by match_ctx_add_entry(). + Note that we might collect inappropriate candidates here. + However, the cost of checking them strictly here is too high, then we + delay these checking for prune_impossible_nodes(). */ + +static reg_errcode_t +internal_function +get_subexp (re_match_context_t *mctx, Idx bkref_node, Idx bkref_str_idx) +{ + const re_dfa_t *const dfa = mctx->dfa; + Idx subexp_num, sub_top_idx; + const char *buf = (const char *) re_string_get_buffer (&mctx->input); + /* Return if we have already checked BKREF_NODE at BKREF_STR_IDX. */ + Idx cache_idx = search_cur_bkref_entry (mctx, bkref_str_idx); + if (cache_idx != REG_MISSING) + { + const struct re_backref_cache_entry *entry + = mctx->bkref_ents + cache_idx; + do + if (entry->node == bkref_node) + return REG_NOERROR; /* We already checked it. */ + while (entry++->more); + } + + subexp_num = dfa->nodes[bkref_node].opr.idx; + + /* For each sub expression */ + for (sub_top_idx = 0; sub_top_idx < mctx->nsub_tops; ++sub_top_idx) + { + reg_errcode_t err; + re_sub_match_top_t *sub_top = mctx->sub_tops[sub_top_idx]; + re_sub_match_last_t *sub_last; + Idx sub_last_idx, sl_str, bkref_str_off; + + if (dfa->nodes[sub_top->node].opr.idx != subexp_num) + continue; /* It isn't related. */ + + sl_str = sub_top->str_idx; + bkref_str_off = bkref_str_idx; + /* At first, check the last node of sub expressions we already + evaluated. */ + for (sub_last_idx = 0; sub_last_idx < sub_top->nlasts; ++sub_last_idx) + { + regoff_t sl_str_diff; + sub_last = sub_top->lasts[sub_last_idx]; + sl_str_diff = sub_last->str_idx - sl_str; + /* The matched string by the sub expression match with the substring + at the back reference? */ + if (sl_str_diff > 0) + { + if (BE (bkref_str_off + sl_str_diff > mctx->input.valid_len, 0)) + { + /* Not enough chars for a successful match. */ + if (bkref_str_off + sl_str_diff > mctx->input.len) + break; + + err = clean_state_log_if_needed (mctx, + bkref_str_off + + sl_str_diff); + if (BE (err != REG_NOERROR, 0)) + return err; + buf = (const char *) re_string_get_buffer (&mctx->input); + } + if (memcmp (buf + bkref_str_off, buf + sl_str, sl_str_diff) != 0) + /* We don't need to search this sub expression any more. */ + break; + } + bkref_str_off += sl_str_diff; + sl_str += sl_str_diff; + err = get_subexp_sub (mctx, sub_top, sub_last, bkref_node, + bkref_str_idx); + + /* Reload buf, since the preceding call might have reallocated + the buffer. */ + buf = (const char *) re_string_get_buffer (&mctx->input); + + if (err == REG_NOMATCH) + continue; + if (BE (err != REG_NOERROR, 0)) + return err; + } + + if (sub_last_idx < sub_top->nlasts) + continue; + if (sub_last_idx > 0) + ++sl_str; + /* Then, search for the other last nodes of the sub expression. */ + for (; sl_str <= bkref_str_idx; ++sl_str) + { + Idx cls_node; + regoff_t sl_str_off; + const re_node_set *nodes; + sl_str_off = sl_str - sub_top->str_idx; + /* The matched string by the sub expression match with the substring + at the back reference? */ + if (sl_str_off > 0) + { + if (BE (bkref_str_off >= mctx->input.valid_len, 0)) + { + /* If we are at the end of the input, we cannot match. */ + if (bkref_str_off >= mctx->input.len) + break; + + err = extend_buffers (mctx); + if (BE (err != REG_NOERROR, 0)) + return err; + + buf = (const char *) re_string_get_buffer (&mctx->input); + } + if (buf [bkref_str_off++] != buf[sl_str - 1]) + break; /* We don't need to search this sub expression + any more. */ + } + if (mctx->state_log[sl_str] == NULL) + continue; + /* Does this state have a ')' of the sub expression? */ + nodes = &mctx->state_log[sl_str]->nodes; + cls_node = find_subexp_node (dfa, nodes, subexp_num, + OP_CLOSE_SUBEXP); + if (cls_node == REG_MISSING) + continue; /* No. */ + if (sub_top->path == NULL) + { + sub_top->path = calloc (sizeof (state_array_t), + sl_str - sub_top->str_idx + 1); + if (sub_top->path == NULL) + return REG_ESPACE; + } + /* Can the OP_OPEN_SUBEXP node arrive the OP_CLOSE_SUBEXP node + in the current context? */ + err = check_arrival (mctx, sub_top->path, sub_top->node, + sub_top->str_idx, cls_node, sl_str, + OP_CLOSE_SUBEXP); + if (err == REG_NOMATCH) + continue; + if (BE (err != REG_NOERROR, 0)) + return err; + sub_last = match_ctx_add_sublast (sub_top, cls_node, sl_str); + if (BE (sub_last == NULL, 0)) + return REG_ESPACE; + err = get_subexp_sub (mctx, sub_top, sub_last, bkref_node, + bkref_str_idx); + if (err == REG_NOMATCH) + continue; + } + } + return REG_NOERROR; +} + +/* Helper functions for get_subexp(). */ + +/* Check SUB_LAST can arrive to the back reference BKREF_NODE at BKREF_STR. + If it can arrive, register the sub expression expressed with SUB_TOP + and SUB_LAST. */ + +static reg_errcode_t +internal_function +get_subexp_sub (re_match_context_t *mctx, const re_sub_match_top_t *sub_top, + re_sub_match_last_t *sub_last, Idx bkref_node, Idx bkref_str) +{ + reg_errcode_t err; + Idx to_idx; + /* Can the subexpression arrive the back reference? */ + err = check_arrival (mctx, &sub_last->path, sub_last->node, + sub_last->str_idx, bkref_node, bkref_str, + OP_OPEN_SUBEXP); + if (err != REG_NOERROR) + return err; + err = match_ctx_add_entry (mctx, bkref_node, bkref_str, sub_top->str_idx, + sub_last->str_idx); + if (BE (err != REG_NOERROR, 0)) + return err; + to_idx = bkref_str + sub_last->str_idx - sub_top->str_idx; + return clean_state_log_if_needed (mctx, to_idx); +} + +/* Find the first node which is '(' or ')' and whose index is SUBEXP_IDX. + Search '(' if FL_OPEN, or search ')' otherwise. + TODO: This function isn't efficient... + Because there might be more than one nodes whose types are + OP_OPEN_SUBEXP and whose index is SUBEXP_IDX, we must check all + nodes. + E.g. RE: (a){2} */ + +static Idx +internal_function +find_subexp_node (const re_dfa_t *dfa, const re_node_set *nodes, + Idx subexp_idx, int type) +{ + Idx cls_idx; + for (cls_idx = 0; cls_idx < nodes->nelem; ++cls_idx) + { + Idx cls_node = nodes->elems[cls_idx]; + const re_token_t *node = dfa->nodes + cls_node; + if (node->type == type + && node->opr.idx == subexp_idx) + return cls_node; + } + return REG_MISSING; +} + +/* Check whether the node TOP_NODE at TOP_STR can arrive to the node + LAST_NODE at LAST_STR. We record the path onto PATH since it will be + heavily reused. + Return REG_NOERROR if it can arrive, or REG_NOMATCH otherwise. */ + +static reg_errcode_t +internal_function +check_arrival (re_match_context_t *mctx, state_array_t *path, Idx top_node, + Idx top_str, Idx last_node, Idx last_str, int type) +{ + const re_dfa_t *const dfa = mctx->dfa; + reg_errcode_t err = REG_NOERROR; + Idx subexp_num, backup_cur_idx, str_idx, null_cnt; + re_dfastate_t *cur_state = NULL; + re_node_set *cur_nodes, next_nodes; + re_dfastate_t **backup_state_log; + unsigned int context; + + subexp_num = dfa->nodes[top_node].opr.idx; + /* Extend the buffer if we need. */ + if (BE (path->alloc < last_str + mctx->max_mb_elem_len + 1, 0)) + { + re_dfastate_t **new_array; + Idx old_alloc = path->alloc; + Idx new_alloc = old_alloc + last_str + mctx->max_mb_elem_len + 1; + if (BE (new_alloc < old_alloc, 0) + || BE (SIZE_MAX / sizeof (re_dfastate_t *) < new_alloc, 0)) + return REG_ESPACE; + new_array = re_realloc (path->array, re_dfastate_t *, new_alloc); + if (BE (new_array == NULL, 0)) + return REG_ESPACE; + path->array = new_array; + path->alloc = new_alloc; + memset (new_array + old_alloc, '\0', + sizeof (re_dfastate_t *) * (path->alloc - old_alloc)); + } + + str_idx = path->next_idx ? path->next_idx : top_str; + + /* Temporary modify MCTX. */ + backup_state_log = mctx->state_log; + backup_cur_idx = mctx->input.cur_idx; + mctx->state_log = path->array; + mctx->input.cur_idx = str_idx; + + /* Setup initial node set. */ + context = re_string_context_at (&mctx->input, str_idx - 1, mctx->eflags); + if (str_idx == top_str) + { + err = re_node_set_init_1 (&next_nodes, top_node); + if (BE (err != REG_NOERROR, 0)) + return err; + err = check_arrival_expand_ecl (dfa, &next_nodes, subexp_num, type); + if (BE (err != REG_NOERROR, 0)) + { + re_node_set_free (&next_nodes); + return err; + } + } + else + { + cur_state = mctx->state_log[str_idx]; + if (cur_state && cur_state->has_backref) + { + err = re_node_set_init_copy (&next_nodes, &cur_state->nodes); + if (BE (err != REG_NOERROR, 0)) + return err; + } + else + re_node_set_init_empty (&next_nodes); + } + if (str_idx == top_str || (cur_state && cur_state->has_backref)) + { + if (next_nodes.nelem) + { + err = expand_bkref_cache (mctx, &next_nodes, str_idx, + subexp_num, type); + if (BE (err != REG_NOERROR, 0)) + { + re_node_set_free (&next_nodes); + return err; + } + } + cur_state = re_acquire_state_context (&err, dfa, &next_nodes, context); + if (BE (cur_state == NULL && err != REG_NOERROR, 0)) + { + re_node_set_free (&next_nodes); + return err; + } + mctx->state_log[str_idx] = cur_state; + } + + for (null_cnt = 0; str_idx < last_str && null_cnt <= mctx->max_mb_elem_len;) + { + re_node_set_empty (&next_nodes); + if (mctx->state_log[str_idx + 1]) + { + err = re_node_set_merge (&next_nodes, + &mctx->state_log[str_idx + 1]->nodes); + if (BE (err != REG_NOERROR, 0)) + { + re_node_set_free (&next_nodes); + return err; + } + } + if (cur_state) + { + err = check_arrival_add_next_nodes (mctx, str_idx, + &cur_state->non_eps_nodes, + &next_nodes); + if (BE (err != REG_NOERROR, 0)) + { + re_node_set_free (&next_nodes); + return err; + } + } + ++str_idx; + if (next_nodes.nelem) + { + err = check_arrival_expand_ecl (dfa, &next_nodes, subexp_num, type); + if (BE (err != REG_NOERROR, 0)) + { + re_node_set_free (&next_nodes); + return err; + } + err = expand_bkref_cache (mctx, &next_nodes, str_idx, + subexp_num, type); + if (BE (err != REG_NOERROR, 0)) + { + re_node_set_free (&next_nodes); + return err; + } + } + context = re_string_context_at (&mctx->input, str_idx - 1, mctx->eflags); + cur_state = re_acquire_state_context (&err, dfa, &next_nodes, context); + if (BE (cur_state == NULL && err != REG_NOERROR, 0)) + { + re_node_set_free (&next_nodes); + return err; + } + mctx->state_log[str_idx] = cur_state; + null_cnt = cur_state == NULL ? null_cnt + 1 : 0; + } + re_node_set_free (&next_nodes); + cur_nodes = (mctx->state_log[last_str] == NULL ? NULL + : &mctx->state_log[last_str]->nodes); + path->next_idx = str_idx; + + /* Fix MCTX. */ + mctx->state_log = backup_state_log; + mctx->input.cur_idx = backup_cur_idx; + + /* Then check the current node set has the node LAST_NODE. */ + if (cur_nodes != NULL && re_node_set_contains (cur_nodes, last_node)) + return REG_NOERROR; + + return REG_NOMATCH; +} + +/* Helper functions for check_arrival. */ + +/* Calculate the destination nodes of CUR_NODES at STR_IDX, and append them + to NEXT_NODES. + TODO: This function is similar to the functions transit_state*(), + however this function has many additional works. + Can't we unify them? */ + +static reg_errcode_t +internal_function +check_arrival_add_next_nodes (re_match_context_t *mctx, Idx str_idx, + re_node_set *cur_nodes, re_node_set *next_nodes) +{ + const re_dfa_t *const dfa = mctx->dfa; + bool ok; + Idx cur_idx; + reg_errcode_t err = REG_NOERROR; + re_node_set union_set; + re_node_set_init_empty (&union_set); + for (cur_idx = 0; cur_idx < cur_nodes->nelem; ++cur_idx) + { + int naccepted = 0; + Idx cur_node = cur_nodes->elems[cur_idx]; +#ifdef DEBUG + re_token_type_t type = dfa->nodes[cur_node].type; + assert (!IS_EPSILON_NODE (type)); +#endif +#ifdef RE_ENABLE_I18N + /* If the node may accept `multi byte'. */ + if (dfa->nodes[cur_node].accept_mb) + { + naccepted = check_node_accept_bytes (dfa, cur_node, &mctx->input, + str_idx); + if (naccepted > 1) + { + re_dfastate_t *dest_state; + Idx next_node = dfa->nexts[cur_node]; + Idx next_idx = str_idx + naccepted; + dest_state = mctx->state_log[next_idx]; + re_node_set_empty (&union_set); + if (dest_state) + { + err = re_node_set_merge (&union_set, &dest_state->nodes); + if (BE (err != REG_NOERROR, 0)) + { + re_node_set_free (&union_set); + return err; + } + } + ok = re_node_set_insert (&union_set, next_node); + if (BE (! ok, 0)) + { + re_node_set_free (&union_set); + return REG_ESPACE; + } + mctx->state_log[next_idx] = re_acquire_state (&err, dfa, + &union_set); + if (BE (mctx->state_log[next_idx] == NULL + && err != REG_NOERROR, 0)) + { + re_node_set_free (&union_set); + return err; + } + } + } +#endif /* RE_ENABLE_I18N */ + if (naccepted + || check_node_accept (mctx, dfa->nodes + cur_node, str_idx)) + { + ok = re_node_set_insert (next_nodes, dfa->nexts[cur_node]); + if (BE (! ok, 0)) + { + re_node_set_free (&union_set); + return REG_ESPACE; + } + } + } + re_node_set_free (&union_set); + return REG_NOERROR; +} + +/* For all the nodes in CUR_NODES, add the epsilon closures of them to + CUR_NODES, however exclude the nodes which are: + - inside the sub expression whose number is EX_SUBEXP, if FL_OPEN. + - out of the sub expression whose number is EX_SUBEXP, if !FL_OPEN. +*/ + +static reg_errcode_t +internal_function +check_arrival_expand_ecl (const re_dfa_t *dfa, re_node_set *cur_nodes, + Idx ex_subexp, int type) +{ + reg_errcode_t err; + Idx idx, outside_node; + re_node_set new_nodes; +#ifdef DEBUG + assert (cur_nodes->nelem); +#endif + err = re_node_set_alloc (&new_nodes, cur_nodes->nelem); + if (BE (err != REG_NOERROR, 0)) + return err; + /* Create a new node set NEW_NODES with the nodes which are epsilon + closures of the node in CUR_NODES. */ + + for (idx = 0; idx < cur_nodes->nelem; ++idx) + { + Idx cur_node = cur_nodes->elems[idx]; + const re_node_set *eclosure = dfa->eclosures + cur_node; + outside_node = find_subexp_node (dfa, eclosure, ex_subexp, type); + if (outside_node == REG_MISSING) + { + /* There are no problematic nodes, just merge them. */ + err = re_node_set_merge (&new_nodes, eclosure); + if (BE (err != REG_NOERROR, 0)) + { + re_node_set_free (&new_nodes); + return err; + } + } + else + { + /* There are problematic nodes, re-calculate incrementally. */ + err = check_arrival_expand_ecl_sub (dfa, &new_nodes, cur_node, + ex_subexp, type); + if (BE (err != REG_NOERROR, 0)) + { + re_node_set_free (&new_nodes); + return err; + } + } + } + re_node_set_free (cur_nodes); + *cur_nodes = new_nodes; + return REG_NOERROR; +} + +/* Helper function for check_arrival_expand_ecl. + Check incrementally the epsilon closure of TARGET, and if it isn't + problematic append it to DST_NODES. */ + +static reg_errcode_t +internal_function +check_arrival_expand_ecl_sub (const re_dfa_t *dfa, re_node_set *dst_nodes, + Idx target, Idx ex_subexp, int type) +{ + Idx cur_node; + for (cur_node = target; !re_node_set_contains (dst_nodes, cur_node);) + { + bool ok; + + if (dfa->nodes[cur_node].type == type + && dfa->nodes[cur_node].opr.idx == ex_subexp) + { + if (type == OP_CLOSE_SUBEXP) + { + ok = re_node_set_insert (dst_nodes, cur_node); + if (BE (! ok, 0)) + return REG_ESPACE; + } + break; + } + ok = re_node_set_insert (dst_nodes, cur_node); + if (BE (! ok, 0)) + return REG_ESPACE; + if (dfa->edests[cur_node].nelem == 0) + break; + if (dfa->edests[cur_node].nelem == 2) + { + reg_errcode_t err; + err = check_arrival_expand_ecl_sub (dfa, dst_nodes, + dfa->edests[cur_node].elems[1], + ex_subexp, type); + if (BE (err != REG_NOERROR, 0)) + return err; + } + cur_node = dfa->edests[cur_node].elems[0]; + } + return REG_NOERROR; +} + + +/* For all the back references in the current state, calculate the + destination of the back references by the appropriate entry + in MCTX->BKREF_ENTS. */ + +static reg_errcode_t +internal_function +expand_bkref_cache (re_match_context_t *mctx, re_node_set *cur_nodes, + Idx cur_str, Idx subexp_num, int type) +{ + const re_dfa_t *const dfa = mctx->dfa; + reg_errcode_t err; + Idx cache_idx_start = search_cur_bkref_entry (mctx, cur_str); + struct re_backref_cache_entry *ent; + + if (cache_idx_start == REG_MISSING) + return REG_NOERROR; + + restart: + ent = mctx->bkref_ents + cache_idx_start; + do + { + Idx to_idx, next_node; + + /* Is this entry ENT is appropriate? */ + if (!re_node_set_contains (cur_nodes, ent->node)) + continue; /* No. */ + + to_idx = cur_str + ent->subexp_to - ent->subexp_from; + /* Calculate the destination of the back reference, and append it + to MCTX->STATE_LOG. */ + if (to_idx == cur_str) + { + /* The backreference did epsilon transit, we must re-check all the + node in the current state. */ + re_node_set new_dests; + reg_errcode_t err2, err3; + next_node = dfa->edests[ent->node].elems[0]; + if (re_node_set_contains (cur_nodes, next_node)) + continue; + err = re_node_set_init_1 (&new_dests, next_node); + err2 = check_arrival_expand_ecl (dfa, &new_dests, subexp_num, type); + err3 = re_node_set_merge (cur_nodes, &new_dests); + re_node_set_free (&new_dests); + if (BE (err != REG_NOERROR || err2 != REG_NOERROR + || err3 != REG_NOERROR, 0)) + { + err = (err != REG_NOERROR ? err + : (err2 != REG_NOERROR ? err2 : err3)); + return err; + } + /* TODO: It is still inefficient... */ + goto restart; + } + else + { + re_node_set union_set; + next_node = dfa->nexts[ent->node]; + if (mctx->state_log[to_idx]) + { + bool ok; + if (re_node_set_contains (&mctx->state_log[to_idx]->nodes, + next_node)) + continue; + err = re_node_set_init_copy (&union_set, + &mctx->state_log[to_idx]->nodes); + ok = re_node_set_insert (&union_set, next_node); + if (BE (err != REG_NOERROR || ! ok, 0)) + { + re_node_set_free (&union_set); + err = err != REG_NOERROR ? err : REG_ESPACE; + return err; + } + } + else + { + err = re_node_set_init_1 (&union_set, next_node); + if (BE (err != REG_NOERROR, 0)) + return err; + } + mctx->state_log[to_idx] = re_acquire_state (&err, dfa, &union_set); + re_node_set_free (&union_set); + if (BE (mctx->state_log[to_idx] == NULL + && err != REG_NOERROR, 0)) + return err; + } + } + while (ent++->more); + return REG_NOERROR; +} + +/* Build transition table for the state. + Return true if successful. */ + +static bool +internal_function +build_trtable (const re_dfa_t *dfa, re_dfastate_t *state) +{ + reg_errcode_t err; + Idx i, j; + int ch; + bool need_word_trtable = false; + bitset_word_t elem, mask; + bool dests_node_malloced = false; + bool dest_states_malloced = false; + Idx ndests; /* Number of the destination states from `state'. */ + re_dfastate_t **trtable; + re_dfastate_t **dest_states = NULL, **dest_states_word, **dest_states_nl; + re_node_set follows, *dests_node; + bitset_t *dests_ch; + bitset_t acceptable; + + struct dests_alloc + { + re_node_set dests_node[SBC_MAX]; + bitset_t dests_ch[SBC_MAX]; + } *dests_alloc; + + /* We build DFA states which corresponds to the destination nodes + from `state'. `dests_node[i]' represents the nodes which i-th + destination state contains, and `dests_ch[i]' represents the + characters which i-th destination state accepts. */ + if (__libc_use_alloca (sizeof (struct dests_alloc))) + dests_alloc = (struct dests_alloc *) alloca (sizeof (struct dests_alloc)); + else + { + dests_alloc = re_malloc (struct dests_alloc, 1); + if (BE (dests_alloc == NULL, 0)) + return false; + dests_node_malloced = true; + } + dests_node = dests_alloc->dests_node; + dests_ch = dests_alloc->dests_ch; + + /* Initialize transiton table. */ + state->word_trtable = state->trtable = NULL; + + /* At first, group all nodes belonging to `state' into several + destinations. */ + ndests = group_nodes_into_DFAstates (dfa, state, dests_node, dests_ch); + if (BE (! REG_VALID_NONZERO_INDEX (ndests), 0)) + { + if (dests_node_malloced) + free (dests_alloc); + if (ndests == 0) + { + state->trtable = (re_dfastate_t **) + calloc (sizeof (re_dfastate_t *), SBC_MAX); + return true; + } + return false; + } + + err = re_node_set_alloc (&follows, ndests + 1); + if (BE (err != REG_NOERROR, 0)) + goto out_free; + + /* Avoid arithmetic overflow in size calculation. */ + if (BE ((((SIZE_MAX - (sizeof (re_node_set) + sizeof (bitset_t)) * SBC_MAX) + / (3 * sizeof (re_dfastate_t *))) + < ndests), + 0)) + goto out_free; + + if (__libc_use_alloca ((sizeof (re_node_set) + sizeof (bitset_t)) * SBC_MAX + + ndests * 3 * sizeof (re_dfastate_t *))) + dest_states = (re_dfastate_t **) + alloca (ndests * 3 * sizeof (re_dfastate_t *)); + else + { + dest_states = (re_dfastate_t **) + malloc (ndests * 3 * sizeof (re_dfastate_t *)); + if (BE (dest_states == NULL, 0)) + { +out_free: + if (dest_states_malloced) + free (dest_states); + re_node_set_free (&follows); + for (i = 0; i < ndests; ++i) + re_node_set_free (dests_node + i); + if (dests_node_malloced) + free (dests_alloc); + return false; + } + dest_states_malloced = true; + } + dest_states_word = dest_states + ndests; + dest_states_nl = dest_states_word + ndests; + bitset_empty (acceptable); + + /* Then build the states for all destinations. */ + for (i = 0; i < ndests; ++i) + { + Idx next_node; + re_node_set_empty (&follows); + /* Merge the follows of this destination states. */ + for (j = 0; j < dests_node[i].nelem; ++j) + { + next_node = dfa->nexts[dests_node[i].elems[j]]; + if (next_node != REG_MISSING) + { + err = re_node_set_merge (&follows, dfa->eclosures + next_node); + if (BE (err != REG_NOERROR, 0)) + goto out_free; + } + } + dest_states[i] = re_acquire_state_context (&err, dfa, &follows, 0); + if (BE (dest_states[i] == NULL && err != REG_NOERROR, 0)) + goto out_free; + /* If the new state has context constraint, + build appropriate states for these contexts. */ + if (dest_states[i]->has_constraint) + { + dest_states_word[i] = re_acquire_state_context (&err, dfa, &follows, + CONTEXT_WORD); + if (BE (dest_states_word[i] == NULL && err != REG_NOERROR, 0)) + goto out_free; + + if (dest_states[i] != dest_states_word[i] && dfa->mb_cur_max > 1) + need_word_trtable = true; + + dest_states_nl[i] = re_acquire_state_context (&err, dfa, &follows, + CONTEXT_NEWLINE); + if (BE (dest_states_nl[i] == NULL && err != REG_NOERROR, 0)) + goto out_free; + } + else + { + dest_states_word[i] = dest_states[i]; + dest_states_nl[i] = dest_states[i]; + } + bitset_merge (acceptable, dests_ch[i]); + } + + if (!BE (need_word_trtable, 0)) + { + /* We don't care about whether the following character is a word + character, or we are in a single-byte character set so we can + discern by looking at the character code: allocate a + 256-entry transition table. */ + trtable = state->trtable = + (re_dfastate_t **) calloc (sizeof (re_dfastate_t *), SBC_MAX); + if (BE (trtable == NULL, 0)) + goto out_free; + + /* For all characters ch...: */ + for (i = 0; i < BITSET_WORDS; ++i) + for (ch = i * BITSET_WORD_BITS, elem = acceptable[i], mask = 1; + elem; + mask <<= 1, elem >>= 1, ++ch) + if (BE (elem & 1, 0)) + { + /* There must be exactly one destination which accepts + character ch. See group_nodes_into_DFAstates. */ + for (j = 0; (dests_ch[j][i] & mask) == 0; ++j) + ; + + /* j-th destination accepts the word character ch. */ + if (dfa->word_char[i] & mask) + trtable[ch] = dest_states_word[j]; + else + trtable[ch] = dest_states[j]; + } + } + else + { + /* We care about whether the following character is a word + character, and we are in a multi-byte character set: discern + by looking at the character code: build two 256-entry + transition tables, one starting at trtable[0] and one + starting at trtable[SBC_MAX]. */ + trtable = state->word_trtable = + (re_dfastate_t **) calloc (sizeof (re_dfastate_t *), 2 * SBC_MAX); + if (BE (trtable == NULL, 0)) + goto out_free; + + /* For all characters ch...: */ + for (i = 0; i < BITSET_WORDS; ++i) + for (ch = i * BITSET_WORD_BITS, elem = acceptable[i], mask = 1; + elem; + mask <<= 1, elem >>= 1, ++ch) + if (BE (elem & 1, 0)) + { + /* There must be exactly one destination which accepts + character ch. See group_nodes_into_DFAstates. */ + for (j = 0; (dests_ch[j][i] & mask) == 0; ++j) + ; + + /* j-th destination accepts the word character ch. */ + trtable[ch] = dest_states[j]; + trtable[ch + SBC_MAX] = dest_states_word[j]; + } + } + + /* new line */ + if (bitset_contain (acceptable, NEWLINE_CHAR)) + { + /* The current state accepts newline character. */ + for (j = 0; j < ndests; ++j) + if (bitset_contain (dests_ch[j], NEWLINE_CHAR)) + { + /* k-th destination accepts newline character. */ + trtable[NEWLINE_CHAR] = dest_states_nl[j]; + if (need_word_trtable) + trtable[NEWLINE_CHAR + SBC_MAX] = dest_states_nl[j]; + /* There must be only one destination which accepts + newline. See group_nodes_into_DFAstates. */ + break; + } + } + + if (dest_states_malloced) + free (dest_states); + + re_node_set_free (&follows); + for (i = 0; i < ndests; ++i) + re_node_set_free (dests_node + i); + + if (dests_node_malloced) + free (dests_alloc); + + return true; +} + +/* Group all nodes belonging to STATE into several destinations. + Then for all destinations, set the nodes belonging to the destination + to DESTS_NODE[i] and set the characters accepted by the destination + to DEST_CH[i]. This function return the number of destinations. */ + +static Idx +internal_function +group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state, + re_node_set *dests_node, bitset_t *dests_ch) +{ + reg_errcode_t err; + bool ok; + Idx i, j, k; + Idx ndests; /* Number of the destinations from `state'. */ + bitset_t accepts; /* Characters a node can accept. */ + const re_node_set *cur_nodes = &state->nodes; + bitset_empty (accepts); + ndests = 0; + + /* For all the nodes belonging to `state', */ + for (i = 0; i < cur_nodes->nelem; ++i) + { + re_token_t *node = &dfa->nodes[cur_nodes->elems[i]]; + re_token_type_t type = node->type; + unsigned int constraint = node->constraint; + + /* Enumerate all single byte character this node can accept. */ + if (type == CHARACTER) + bitset_set (accepts, node->opr.c); + else if (type == SIMPLE_BRACKET) + { + bitset_merge (accepts, node->opr.sbcset); + } + else if (type == OP_PERIOD) + { +#ifdef RE_ENABLE_I18N + if (dfa->mb_cur_max > 1) + bitset_merge (accepts, dfa->sb_char); + else +#endif + bitset_set_all (accepts); + if (!(dfa->syntax & RE_DOT_NEWLINE)) + bitset_clear (accepts, '\n'); + if (dfa->syntax & RE_DOT_NOT_NULL) + bitset_clear (accepts, '\0'); + } +#ifdef RE_ENABLE_I18N + else if (type == OP_UTF8_PERIOD) + { + if (ASCII_CHARS % BITSET_WORD_BITS == 0) + memset (accepts, -1, ASCII_CHARS / CHAR_BIT); + else + bitset_merge (accepts, utf8_sb_map); + if (!(dfa->syntax & RE_DOT_NEWLINE)) + bitset_clear (accepts, '\n'); + if (dfa->syntax & RE_DOT_NOT_NULL) + bitset_clear (accepts, '\0'); + } +#endif + else + continue; + + /* Check the `accepts' and sift the characters which are not + match it the context. */ + if (constraint) + { + if (constraint & NEXT_NEWLINE_CONSTRAINT) + { + bool accepts_newline = bitset_contain (accepts, NEWLINE_CHAR); + bitset_empty (accepts); + if (accepts_newline) + bitset_set (accepts, NEWLINE_CHAR); + else + continue; + } + if (constraint & NEXT_ENDBUF_CONSTRAINT) + { + bitset_empty (accepts); + continue; + } + + if (constraint & NEXT_WORD_CONSTRAINT) + { + bitset_word_t any_set = 0; + if (type == CHARACTER && !node->word_char) + { + bitset_empty (accepts); + continue; + } +#ifdef RE_ENABLE_I18N + if (dfa->mb_cur_max > 1) + for (j = 0; j < BITSET_WORDS; ++j) + any_set |= (accepts[j] &= (dfa->word_char[j] | ~dfa->sb_char[j])); + else +#endif + for (j = 0; j < BITSET_WORDS; ++j) + any_set |= (accepts[j] &= dfa->word_char[j]); + if (!any_set) + continue; + } + if (constraint & NEXT_NOTWORD_CONSTRAINT) + { + bitset_word_t any_set = 0; + if (type == CHARACTER && node->word_char) + { + bitset_empty (accepts); + continue; + } +#ifdef RE_ENABLE_I18N + if (dfa->mb_cur_max > 1) + for (j = 0; j < BITSET_WORDS; ++j) + any_set |= (accepts[j] &= ~(dfa->word_char[j] & dfa->sb_char[j])); + else +#endif + for (j = 0; j < BITSET_WORDS; ++j) + any_set |= (accepts[j] &= ~dfa->word_char[j]); + if (!any_set) + continue; + } + } + + /* Then divide `accepts' into DFA states, or create a new + state. Above, we make sure that accepts is not empty. */ + for (j = 0; j < ndests; ++j) + { + bitset_t intersec; /* Intersection sets, see below. */ + bitset_t remains; + /* Flags, see below. */ + bitset_word_t has_intersec, not_subset, not_consumed; + + /* Optimization, skip if this state doesn't accept the character. */ + if (type == CHARACTER && !bitset_contain (dests_ch[j], node->opr.c)) + continue; + + /* Enumerate the intersection set of this state and `accepts'. */ + has_intersec = 0; + for (k = 0; k < BITSET_WORDS; ++k) + has_intersec |= intersec[k] = accepts[k] & dests_ch[j][k]; + /* And skip if the intersection set is empty. */ + if (!has_intersec) + continue; + + /* Then check if this state is a subset of `accepts'. */ + not_subset = not_consumed = 0; + for (k = 0; k < BITSET_WORDS; ++k) + { + not_subset |= remains[k] = ~accepts[k] & dests_ch[j][k]; + not_consumed |= accepts[k] = accepts[k] & ~dests_ch[j][k]; + } + + /* If this state isn't a subset of `accepts', create a + new group state, which has the `remains'. */ + if (not_subset) + { + bitset_copy (dests_ch[ndests], remains); + bitset_copy (dests_ch[j], intersec); + err = re_node_set_init_copy (dests_node + ndests, &dests_node[j]); + if (BE (err != REG_NOERROR, 0)) + goto error_return; + ++ndests; + } + + /* Put the position in the current group. */ + ok = re_node_set_insert (&dests_node[j], cur_nodes->elems[i]); + if (BE (! ok, 0)) + goto error_return; + + /* If all characters are consumed, go to next node. */ + if (!not_consumed) + break; + } + /* Some characters remain, create a new group. */ + if (j == ndests) + { + bitset_copy (dests_ch[ndests], accepts); + err = re_node_set_init_1 (dests_node + ndests, cur_nodes->elems[i]); + if (BE (err != REG_NOERROR, 0)) + goto error_return; + ++ndests; + bitset_empty (accepts); + } + } + return ndests; + error_return: + for (j = 0; j < ndests; ++j) + re_node_set_free (dests_node + j); + return REG_MISSING; +} + +#ifdef RE_ENABLE_I18N +/* Check how many bytes the node `dfa->nodes[node_idx]' accepts. + Return the number of the bytes the node accepts. + STR_IDX is the current index of the input string. + + This function handles the nodes which can accept one character, or + one collating element like '.', '[a-z]', opposite to the other nodes + can only accept one byte. */ + +static int +internal_function +check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx, + const re_string_t *input, Idx str_idx) +{ + const re_token_t *node = dfa->nodes + node_idx; + int char_len, elem_len; + Idx i; + + if (BE (node->type == OP_UTF8_PERIOD, 0)) + { + unsigned char c = re_string_byte_at (input, str_idx), d; + if (BE (c < 0xc2, 1)) + return 0; + + if (str_idx + 2 > input->len) + return 0; + + d = re_string_byte_at (input, str_idx + 1); + if (c < 0xe0) + return (d < 0x80 || d > 0xbf) ? 0 : 2; + else if (c < 0xf0) + { + char_len = 3; + if (c == 0xe0 && d < 0xa0) + return 0; + } + else if (c < 0xf8) + { + char_len = 4; + if (c == 0xf0 && d < 0x90) + return 0; + } + else if (c < 0xfc) + { + char_len = 5; + if (c == 0xf8 && d < 0x88) + return 0; + } + else if (c < 0xfe) + { + char_len = 6; + if (c == 0xfc && d < 0x84) + return 0; + } + else + return 0; + + if (str_idx + char_len > input->len) + return 0; + + for (i = 1; i < char_len; ++i) + { + d = re_string_byte_at (input, str_idx + i); + if (d < 0x80 || d > 0xbf) + return 0; + } + return char_len; + } + + char_len = re_string_char_size_at (input, str_idx); + if (node->type == OP_PERIOD) + { + if (char_len <= 1) + return 0; + /* FIXME: I don't think this if is needed, as both '\n' + and '\0' are char_len == 1. */ + /* '.' accepts any one character except the following two cases. */ + if ((!(dfa->syntax & RE_DOT_NEWLINE) && + re_string_byte_at (input, str_idx) == '\n') || + ((dfa->syntax & RE_DOT_NOT_NULL) && + re_string_byte_at (input, str_idx) == '\0')) + return 0; + return char_len; + } + + elem_len = re_string_elem_size_at (input, str_idx); + if ((elem_len <= 1 && char_len <= 1) || char_len == 0) + return 0; + + if (node->type == COMPLEX_BRACKET) + { + const re_charset_t *cset = node->opr.mbcset; +# ifdef _LIBC + const unsigned char *pin + = ((const unsigned char *) re_string_get_buffer (input) + str_idx); + Idx j; + uint32_t nrules; +# endif /* _LIBC */ + int match_len = 0; + wchar_t wc = ((cset->nranges || cset->nchar_classes || cset->nmbchars) + ? re_string_wchar_at (input, str_idx) : 0); + + /* match with multibyte character? */ + for (i = 0; i < cset->nmbchars; ++i) + if (wc == cset->mbchars[i]) + { + match_len = char_len; + goto check_node_accept_bytes_match; + } + /* match with character_class? */ + for (i = 0; i < cset->nchar_classes; ++i) + { + wctype_t wt = cset->char_classes[i]; + if (__iswctype (wc, wt)) + { + match_len = char_len; + goto check_node_accept_bytes_match; + } + } + +# ifdef _LIBC + nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES); + if (nrules != 0) + { + unsigned int in_collseq = 0; + const int32_t *table, *indirect; + const unsigned char *weights, *extra; + const char *collseqwc; + int32_t idx; + /* This #include defines a local function! */ +# include + + /* match with collating_symbol? */ + if (cset->ncoll_syms) + extra = (const unsigned char *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB); + for (i = 0; i < cset->ncoll_syms; ++i) + { + const unsigned char *coll_sym = extra + cset->coll_syms[i]; + /* Compare the length of input collating element and + the length of current collating element. */ + if (*coll_sym != elem_len) + continue; + /* Compare each bytes. */ + for (j = 0; j < *coll_sym; j++) + if (pin[j] != coll_sym[1 + j]) + break; + if (j == *coll_sym) + { + /* Match if every bytes is equal. */ + match_len = j; + goto check_node_accept_bytes_match; + } + } + + if (cset->nranges) + { + if (elem_len <= char_len) + { + collseqwc = _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQWC); + in_collseq = __collseq_table_lookup (collseqwc, wc); + } + else + in_collseq = find_collation_sequence_value (pin, elem_len); + } + /* match with range expression? */ + for (i = 0; i < cset->nranges; ++i) + if (cset->range_starts[i] <= in_collseq + && in_collseq <= cset->range_ends[i]) + { + match_len = elem_len; + goto check_node_accept_bytes_match; + } + + /* match with equivalence_class? */ + if (cset->nequiv_classes) + { + const unsigned char *cp = pin; + table = (const int32_t *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB); + weights = (const unsigned char *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB); + extra = (const unsigned char *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB); + indirect = (const int32_t *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB); + idx = findidx (&cp); + if (idx > 0) + for (i = 0; i < cset->nequiv_classes; ++i) + { + int32_t equiv_class_idx = cset->equiv_classes[i]; + size_t weight_len = weights[idx]; + if (weight_len == weights[equiv_class_idx]) + { + Idx cnt = 0; + while (cnt <= weight_len + && (weights[equiv_class_idx + 1 + cnt] + == weights[idx + 1 + cnt])) + ++cnt; + if (cnt > weight_len) + { + match_len = elem_len; + goto check_node_accept_bytes_match; + } + } + } + } + } + else +# endif /* _LIBC */ + { + /* match with range expression? */ +#if __GNUC__ >= 2 && ! (__STDC_VERSION__ < 199901L && __STRICT_ANSI__) + wchar_t cmp_buf[] = {L'\0', L'\0', wc, L'\0', L'\0', L'\0'}; +#else + wchar_t cmp_buf[] = {L'\0', L'\0', L'\0', L'\0', L'\0', L'\0'}; + cmp_buf[2] = wc; +#endif + for (i = 0; i < cset->nranges; ++i) + { + cmp_buf[0] = cset->range_starts[i]; + cmp_buf[4] = cset->range_ends[i]; + if (wcscoll (cmp_buf, cmp_buf + 2) <= 0 + && wcscoll (cmp_buf + 2, cmp_buf + 4) <= 0) + { + match_len = char_len; + goto check_node_accept_bytes_match; + } + } + } + check_node_accept_bytes_match: + if (!cset->non_match) + return match_len; + else + { + if (match_len > 0) + return 0; + else + return (elem_len > char_len) ? elem_len : char_len; + } + } + return 0; +} + +# ifdef _LIBC +static unsigned int +internal_function +find_collation_sequence_value (const unsigned char *mbs, size_t mbs_len) +{ + uint32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES); + if (nrules == 0) + { + if (mbs_len == 1) + { + /* No valid character. Match it as a single byte character. */ + const unsigned char *collseq = (const unsigned char *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQMB); + return collseq[mbs[0]]; + } + return UINT_MAX; + } + else + { + int32_t idx; + const unsigned char *extra = (const unsigned char *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB); + int32_t extrasize = (const unsigned char *) + _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB + 1) - extra; + + for (idx = 0; idx < extrasize;) + { + int mbs_cnt; + bool found = false; + int32_t elem_mbs_len; + /* Skip the name of collating element name. */ + idx = idx + extra[idx] + 1; + elem_mbs_len = extra[idx++]; + if (mbs_len == elem_mbs_len) + { + for (mbs_cnt = 0; mbs_cnt < elem_mbs_len; ++mbs_cnt) + if (extra[idx + mbs_cnt] != mbs[mbs_cnt]) + break; + if (mbs_cnt == elem_mbs_len) + /* Found the entry. */ + found = true; + } + /* Skip the byte sequence of the collating element. */ + idx += elem_mbs_len; + /* Adjust for the alignment. */ + idx = (idx + 3) & ~3; + /* Skip the collation sequence value. */ + idx += sizeof (uint32_t); + /* Skip the wide char sequence of the collating element. */ + idx = idx + sizeof (uint32_t) * (extra[idx] + 1); + /* If we found the entry, return the sequence value. */ + if (found) + return *(uint32_t *) (extra + idx); + /* Skip the collation sequence value. */ + idx += sizeof (uint32_t); + } + return UINT_MAX; + } +} +# endif /* _LIBC */ +#endif /* RE_ENABLE_I18N */ + +/* Check whether the node accepts the byte which is IDX-th + byte of the INPUT. */ + +static bool +internal_function +check_node_accept (const re_match_context_t *mctx, const re_token_t *node, + Idx idx) +{ + unsigned char ch; + ch = re_string_byte_at (&mctx->input, idx); + switch (node->type) + { + case CHARACTER: + if (node->opr.c != ch) + return false; + break; + + case SIMPLE_BRACKET: + if (!bitset_contain (node->opr.sbcset, ch)) + return false; + break; + +#ifdef RE_ENABLE_I18N + case OP_UTF8_PERIOD: + if (ch >= ASCII_CHARS) + return false; + /* FALLTHROUGH */ +#endif + case OP_PERIOD: + if ((ch == '\n' && !(mctx->dfa->syntax & RE_DOT_NEWLINE)) + || (ch == '\0' && (mctx->dfa->syntax & RE_DOT_NOT_NULL))) + return false; + break; + + default: + return false; + } + + if (node->constraint) + { + /* The node has constraints. Check whether the current context + satisfies the constraints. */ + unsigned int context = re_string_context_at (&mctx->input, idx, + mctx->eflags); + if (NOT_SATISFY_NEXT_CONSTRAINT (node->constraint, context)) + return false; + } + + return true; +} + +/* Extend the buffers, if the buffers have run out. */ + +static reg_errcode_t +internal_function +extend_buffers (re_match_context_t *mctx) +{ + reg_errcode_t ret; + re_string_t *pstr = &mctx->input; + + /* Avoid overflow. */ + if (BE (SIZE_MAX / 2 / sizeof (re_dfastate_t *) <= pstr->bufs_len, 0)) + return REG_ESPACE; + + /* Double the lengthes of the buffers. */ + ret = re_string_realloc_buffers (pstr, pstr->bufs_len * 2); + if (BE (ret != REG_NOERROR, 0)) + return ret; + + if (mctx->state_log != NULL) + { + /* And double the length of state_log. */ + /* XXX We have no indication of the size of this buffer. If this + allocation fail we have no indication that the state_log array + does not have the right size. */ + re_dfastate_t **new_array = re_realloc (mctx->state_log, re_dfastate_t *, + pstr->bufs_len + 1); + if (BE (new_array == NULL, 0)) + return REG_ESPACE; + mctx->state_log = new_array; + } + + /* Then reconstruct the buffers. */ + if (pstr->icase) + { +#ifdef RE_ENABLE_I18N + if (pstr->mb_cur_max > 1) + { + ret = build_wcs_upper_buffer (pstr); + if (BE (ret != REG_NOERROR, 0)) + return ret; + } + else +#endif /* RE_ENABLE_I18N */ + build_upper_buffer (pstr); + } + else + { +#ifdef RE_ENABLE_I18N + if (pstr->mb_cur_max > 1) + build_wcs_buffer (pstr); + else +#endif /* RE_ENABLE_I18N */ + { + if (pstr->trans != NULL) + re_string_translate_buffer (pstr); + } + } + return REG_NOERROR; +} + + +/* Functions for matching context. */ + +/* Initialize MCTX. */ + +static reg_errcode_t +internal_function +match_ctx_init (re_match_context_t *mctx, int eflags, Idx n) +{ + mctx->eflags = eflags; + mctx->match_last = REG_MISSING; + if (n > 0) + { + /* Avoid overflow. */ + size_t max_object_size = + MAX (sizeof (struct re_backref_cache_entry), + sizeof (re_sub_match_top_t *)); + if (BE (SIZE_MAX / max_object_size < n, 0)) + return REG_ESPACE; + + mctx->bkref_ents = re_malloc (struct re_backref_cache_entry, n); + mctx->sub_tops = re_malloc (re_sub_match_top_t *, n); + if (BE (mctx->bkref_ents == NULL || mctx->sub_tops == NULL, 0)) + return REG_ESPACE; + } + /* Already zero-ed by the caller. + else + mctx->bkref_ents = NULL; + mctx->nbkref_ents = 0; + mctx->nsub_tops = 0; */ + mctx->abkref_ents = n; + mctx->max_mb_elem_len = 1; + mctx->asub_tops = n; + return REG_NOERROR; +} + +/* Clean the entries which depend on the current input in MCTX. + This function must be invoked when the matcher changes the start index + of the input, or changes the input string. */ + +static void +internal_function +match_ctx_clean (re_match_context_t *mctx) +{ + Idx st_idx; + for (st_idx = 0; st_idx < mctx->nsub_tops; ++st_idx) + { + Idx sl_idx; + re_sub_match_top_t *top = mctx->sub_tops[st_idx]; + for (sl_idx = 0; sl_idx < top->nlasts; ++sl_idx) + { + re_sub_match_last_t *last = top->lasts[sl_idx]; + re_free (last->path.array); + re_free (last); + } + re_free (top->lasts); + if (top->path) + { + re_free (top->path->array); + re_free (top->path); + } + free (top); + } + + mctx->nsub_tops = 0; + mctx->nbkref_ents = 0; +} + +/* Free all the memory associated with MCTX. */ + +static void +internal_function +match_ctx_free (re_match_context_t *mctx) +{ + /* First, free all the memory associated with MCTX->SUB_TOPS. */ + match_ctx_clean (mctx); + re_free (mctx->sub_tops); + re_free (mctx->bkref_ents); +} + +/* Add a new backreference entry to MCTX. + Note that we assume that caller never call this function with duplicate + entry, and call with STR_IDX which isn't smaller than any existing entry. +*/ + +static reg_errcode_t +internal_function +match_ctx_add_entry (re_match_context_t *mctx, Idx node, Idx str_idx, Idx from, + Idx to) +{ + if (mctx->nbkref_ents >= mctx->abkref_ents) + { + struct re_backref_cache_entry* new_entry; + new_entry = re_realloc (mctx->bkref_ents, struct re_backref_cache_entry, + mctx->abkref_ents * 2); + if (BE (new_entry == NULL, 0)) + { + re_free (mctx->bkref_ents); + return REG_ESPACE; + } + mctx->bkref_ents = new_entry; + memset (mctx->bkref_ents + mctx->nbkref_ents, '\0', + sizeof (struct re_backref_cache_entry) * mctx->abkref_ents); + mctx->abkref_ents *= 2; + } + if (mctx->nbkref_ents > 0 + && mctx->bkref_ents[mctx->nbkref_ents - 1].str_idx == str_idx) + mctx->bkref_ents[mctx->nbkref_ents - 1].more = 1; + + mctx->bkref_ents[mctx->nbkref_ents].node = node; + mctx->bkref_ents[mctx->nbkref_ents].str_idx = str_idx; + mctx->bkref_ents[mctx->nbkref_ents].subexp_from = from; + mctx->bkref_ents[mctx->nbkref_ents].subexp_to = to; + + /* This is a cache that saves negative results of check_dst_limits_calc_pos. + If bit N is clear, means that this entry won't epsilon-transition to + an OP_OPEN_SUBEXP or OP_CLOSE_SUBEXP for the N+1-th subexpression. If + it is set, check_dst_limits_calc_pos_1 will recurse and try to find one + such node. + + A backreference does not epsilon-transition unless it is empty, so set + to all zeros if FROM != TO. */ + mctx->bkref_ents[mctx->nbkref_ents].eps_reachable_subexps_map + = (from == to ? -1 : 0); + + mctx->bkref_ents[mctx->nbkref_ents++].more = 0; + if (mctx->max_mb_elem_len < to - from) + mctx->max_mb_elem_len = to - from; + return REG_NOERROR; +} + +/* Return the first entry with the same str_idx, or REG_MISSING if none is + found. Note that MCTX->BKREF_ENTS is already sorted by MCTX->STR_IDX. */ + +static Idx +internal_function +search_cur_bkref_entry (const re_match_context_t *mctx, Idx str_idx) +{ + Idx left, right, mid, last; + last = right = mctx->nbkref_ents; + for (left = 0; left < right;) + { + mid = (left + right) / 2; + if (mctx->bkref_ents[mid].str_idx < str_idx) + left = mid + 1; + else + right = mid; + } + if (left < last && mctx->bkref_ents[left].str_idx == str_idx) + return left; + else + return REG_MISSING; +} + +/* Register the node NODE, whose type is OP_OPEN_SUBEXP, and which matches + at STR_IDX. */ + +static reg_errcode_t +internal_function +match_ctx_add_subtop (re_match_context_t *mctx, Idx node, Idx str_idx) +{ +#ifdef DEBUG + assert (mctx->sub_tops != NULL); + assert (mctx->asub_tops > 0); +#endif + if (BE (mctx->nsub_tops == mctx->asub_tops, 0)) + { + Idx new_asub_tops = mctx->asub_tops * 2; + re_sub_match_top_t **new_array = re_realloc (mctx->sub_tops, + re_sub_match_top_t *, + new_asub_tops); + if (BE (new_array == NULL, 0)) + return REG_ESPACE; + mctx->sub_tops = new_array; + mctx->asub_tops = new_asub_tops; + } + mctx->sub_tops[mctx->nsub_tops] = calloc (1, sizeof (re_sub_match_top_t)); + if (BE (mctx->sub_tops[mctx->nsub_tops] == NULL, 0)) + return REG_ESPACE; + mctx->sub_tops[mctx->nsub_tops]->node = node; + mctx->sub_tops[mctx->nsub_tops++]->str_idx = str_idx; + return REG_NOERROR; +} + +/* Register the node NODE, whose type is OP_CLOSE_SUBEXP, and which matches + at STR_IDX, whose corresponding OP_OPEN_SUBEXP is SUB_TOP. */ + +static re_sub_match_last_t * +internal_function +match_ctx_add_sublast (re_sub_match_top_t *subtop, Idx node, Idx str_idx) +{ + re_sub_match_last_t *new_entry; + if (BE (subtop->nlasts == subtop->alasts, 0)) + { + Idx new_alasts = 2 * subtop->alasts + 1; + re_sub_match_last_t **new_array = re_realloc (subtop->lasts, + re_sub_match_last_t *, + new_alasts); + if (BE (new_array == NULL, 0)) + return NULL; + subtop->lasts = new_array; + subtop->alasts = new_alasts; + } + new_entry = calloc (1, sizeof (re_sub_match_last_t)); + if (BE (new_entry != NULL, 1)) + { + subtop->lasts[subtop->nlasts] = new_entry; + new_entry->node = node; + new_entry->str_idx = str_idx; + ++subtop->nlasts; + } + return new_entry; +} + +static void +internal_function +sift_ctx_init (re_sift_context_t *sctx, re_dfastate_t **sifted_sts, + re_dfastate_t **limited_sts, Idx last_node, Idx last_str_idx) +{ + sctx->sifted_states = sifted_sts; + sctx->limited_states = limited_sts; + sctx->last_node = last_node; + sctx->last_str_idx = last_str_idx; + re_node_set_init_empty (&sctx->limits); +} diff --git a/src/bin/findutils/gnulib/lib/rpmatch.c b/src/bin/findutils/gnulib/lib/rpmatch.c new file mode 100644 index 0000000000..826bc4c5e5 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/rpmatch.c @@ -0,0 +1,78 @@ +/* Determine whether string value is affirmation or negative response + according to current locale's data. + + Copyright (C) 1996, 1998, 2000, 2002, 2003, 2006 Free Software + Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include +#include + +#if ENABLE_NLS +# include +# include +# include +# include "gettext.h" +# define _(msgid) gettext (msgid) + +static int +try (const char *response, const char *pattern, const int match, + const int nomatch, const char **lastp, regex_t *re) +{ + if (pattern != *lastp) + { + /* The pattern has changed. */ + if (*lastp) + { + /* Free the old compiled pattern. */ + regfree (re); + *lastp = NULL; + } + /* Compile the pattern and cache it for future runs. */ + if (regcomp (re, pattern, REG_EXTENDED) != 0) + return -1; + *lastp = pattern; + } + + /* See if the regular expression matches RESPONSE. */ + return regexec (re, response, 0, NULL, 0) == 0 ? match : nomatch; +} +#endif + + +int +rpmatch (const char *response) +{ +#if ENABLE_NLS + /* Match against one of the response patterns, compiling the pattern + first if necessary. */ + + /* We cache the response patterns and compiled regexps here. */ + static const char *yesexpr, *noexpr; + static regex_t yesre, nore; + int result; + + return ((result = try (response, _("^[yY]"), 1, 0, + &yesexpr, &yesre)) + ? result + : try (response, _("^[nN]"), 0, -1, &noexpr, &nore)); +#else + /* Test against "^[yY]" and "^[nN]", hardcoded to avoid requiring regex */ + return (*response == 'y' || *response == 'Y' ? 1 + : *response == 'n' || *response == 'N' ? 0 : -1); +#endif +} diff --git a/src/bin/findutils/gnulib/lib/same-inode.h b/src/bin/findutils/gnulib/lib/same-inode.h new file mode 100644 index 0000000000..063271174c --- /dev/null +++ b/src/bin/findutils/gnulib/lib/same-inode.h @@ -0,0 +1,25 @@ +/* Determine whether two stat buffers refer to the same file. + + Copyright (C) 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef SAME_INODE_H +# define SAME_INODE_H 1 + +# define SAME_INODE(Stat_buf_1, Stat_buf_2) \ + ((Stat_buf_1).st_ino == (Stat_buf_2).st_ino \ + && (Stat_buf_1).st_dev == (Stat_buf_2).st_dev) + +#endif diff --git a/src/bin/findutils/gnulib/lib/same.c b/src/bin/findutils/gnulib/lib/same.c new file mode 100644 index 0000000000..af3a95efb7 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/same.c @@ -0,0 +1,125 @@ +/* Determine whether two file names refer to the same file. + + Copyright (C) 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006 Free + Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#ifndef _POSIX_NAME_MAX +# define _POSIX_NAME_MAX 14 +#endif + +#include "same.h" +#include "dirname.h" +#include "error.h" +#include "same-inode.h" +#include "xalloc.h" + +#ifndef MIN +# define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +/* Return nonzero if SOURCE and DEST point to the same name in the same + directory. */ + +bool +same_name (const char *source, const char *dest) +{ + /* Compare the basenames. */ + char const *source_basename = last_component (source); + char const *dest_basename = last_component (dest); + size_t source_baselen = base_len (source_basename); + size_t dest_baselen = base_len (dest_basename); + bool identical_basenames = + (source_baselen == dest_baselen + && memcmp (source_basename, dest_basename, dest_baselen) == 0); + bool compare_dirs = identical_basenames; + bool same = false; + +#if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX + /* This implementation silently truncates components of file names. If + the base names might be truncated, check whether the truncated + base names are the same, while checking the directories. */ + size_t slen_max = HAVE_LONG_FILE_NAMES ? 255 : _POSIX_NAME_MAX; + size_t min_baselen = MIN (source_baselen, dest_baselen); + if (slen_max <= min_baselen + && memcmp (source_basename, dest_basename, slen_max) == 0) + compare_dirs = true; +#endif + + if (compare_dirs) + { + struct stat source_dir_stats; + struct stat dest_dir_stats; + char *source_dirname, *dest_dirname; + + /* Compare the parent directories (via the device and inode numbers). */ + source_dirname = dir_name (source); + dest_dirname = dir_name (dest); + + if (stat (source_dirname, &source_dir_stats)) + { + /* Shouldn't happen. */ + error (1, errno, "%s", source_dirname); + } + + if (stat (dest_dirname, &dest_dir_stats)) + { + /* Shouldn't happen. */ + error (1, errno, "%s", dest_dirname); + } + + same = SAME_INODE (source_dir_stats, dest_dir_stats); + +#if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX + if (same && ! identical_basenames) + { + long name_max = (errno = 0, pathconf (dest_dirname, _PC_NAME_MAX)); + if (name_max < 0) + { + if (errno) + { + /* Shouldn't happen. */ + error (1, errno, "%s", dest_dirname); + } + same = false; + } + else + same = (name_max <= min_baselen + && memcmp (source_basename, dest_basename, name_max) == 0); + } +#endif + + free (source_dirname); + free (dest_dirname); + } + + return same; +} diff --git a/src/bin/findutils/gnulib/lib/same.h b/src/bin/findutils/gnulib/lib/same.h new file mode 100644 index 0000000000..56e51cffc1 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/same.h @@ -0,0 +1,26 @@ +/* Determine whether two file names refer to the same file. + + Copyright (C) 1997, 1998, 1999, 2000, 2003, 2004 Free Software + Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef SAME_H_ +# define SAME_H_ 1 + +# include + +bool same_name (const char *source, const char *dest); + +#endif /* SAME_H_ */ diff --git a/src/bin/findutils/gnulib/lib/save-cwd.c b/src/bin/findutils/gnulib/lib/save-cwd.c new file mode 100644 index 0000000000..7618f090dc --- /dev/null +++ b/src/bin/findutils/gnulib/lib/save-cwd.c @@ -0,0 +1,102 @@ +/* save-cwd.c -- Save and restore current working directory. + + Copyright (C) 1995, 1997, 1998, 2003, 2004, 2005, 2006 Free + Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Jim Meyering. */ + +#include + +#include "save-cwd.h" + +#include +#include +#include +#include +#include + +#include "chdir-long.h" +#include "fcntl--.h" +#include "xgetcwd.h" + +/* On systems without the fchdir function (WOE), pretend that open + always returns -1 so that save_cwd resorts to using xgetcwd. + Since chdir_long requires fchdir, use chdir instead. */ +#if !HAVE_FCHDIR +# undef open +# define open(File, Flags) (-1) +# undef fchdir +# define fchdir(Fd) (abort (), -1) +# undef chdir_long +# define chdir_long(Dir) chdir (Dir) +#endif + +/* Record the location of the current working directory in CWD so that + the program may change to other directories and later use restore_cwd + to return to the recorded location. This function may allocate + space using malloc (via xgetcwd) or leave a file descriptor open; + use free_cwd to perform the necessary free or close. Upon failure, + no memory is allocated, any locally opened file descriptors are + closed; return non-zero -- in that case, free_cwd need not be + called, but doing so is ok. Otherwise, return zero. + + The `raison d'etre' for this interface is that the working directory + is sometimes inaccessible, and getcwd is not robust or as efficient. + So, we prefer to use the open/fchdir approach, but fall back on + getcwd if necessary. + + Some systems lack fchdir altogether: e.g., OS/2, pre-2001 Cygwin, + SCO Xenix. Also, SunOS 4 and Irix 5.3 provide the function, yet it + doesn't work for partitions on which auditing is enabled. If + you're still using an obsolete system with these problems, please + send email to the maintainer of this code. */ + +int +save_cwd (struct saved_cwd *cwd) +{ + cwd->name = NULL; + + cwd->desc = open (".", O_RDONLY); + if (cwd->desc < 0) + { + cwd->name = xgetcwd (); + return cwd->name ? 0 : -1; + } + + return 0; +} + +/* Change to recorded location, CWD, in directory hierarchy. + Upon failure, return -1 (errno is set by chdir or fchdir). + Upon success, return zero. */ + +int +restore_cwd (const struct saved_cwd *cwd) +{ + if (0 <= cwd->desc) + return fchdir (cwd->desc); + else + return chdir_long (cwd->name); +} + +void +free_cwd (struct saved_cwd *cwd) +{ + if (cwd->desc >= 0) + close (cwd->desc); + if (cwd->name) + free (cwd->name); +} diff --git a/src/bin/findutils/gnulib/lib/save-cwd.h b/src/bin/findutils/gnulib/lib/save-cwd.h new file mode 100644 index 0000000000..e23eb725fd --- /dev/null +++ b/src/bin/findutils/gnulib/lib/save-cwd.h @@ -0,0 +1,33 @@ +/* Save and restore current working directory. + + Copyright (C) 1995, 1997, 1998, 2003 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Jim Meyering. */ + +#ifndef SAVE_CWD_H +# define SAVE_CWD_H 1 + +struct saved_cwd + { + int desc; + char *name; + }; + +int save_cwd (struct saved_cwd *cwd); +int restore_cwd (const struct saved_cwd *cwd); +void free_cwd (struct saved_cwd *cwd); + +#endif /* SAVE_CWD_H */ diff --git a/src/bin/findutils/gnulib/lib/savedir.c b/src/bin/findutils/gnulib/lib/savedir.c new file mode 100644 index 0000000000..b837414335 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/savedir.c @@ -0,0 +1,136 @@ +/* savedir.c -- save the list of files in a directory in a string + + Copyright (C) 1990, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, + 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by David MacKenzie . */ + +#include + +#include "savedir.h" + +#include + +#include + +#include +#ifndef _D_EXACT_NAMLEN +# define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name) +#endif + +#include +#include +#include + +#include "openat.h" +#include "xalloc.h" + +#ifndef NAME_SIZE_DEFAULT +# define NAME_SIZE_DEFAULT 512 +#endif + +/* The results of opendir() in this file are not used with dirfd and fchdir, + therefore save some unnecessary work in fchdir.c. */ +#undef opendir +#undef closedir + +/* Return a freshly allocated string containing the file names + in directory DIRP, separated by '\0' characters; + the end is marked by two '\0' characters in a row. + Return NULL (setting errno) if DIRP cannot be read or closed. + If DIRP is NULL, return NULL without affecting errno. */ + +static char * +savedirstream (DIR *dirp) +{ + char *name_space; + size_t allocated = NAME_SIZE_DEFAULT; + size_t used = 0; + int save_errno; + + if (dirp == NULL) + return NULL; + + name_space = xmalloc (allocated); + + for (;;) + { + struct dirent const *dp; + char const *entry; + + errno = 0; + dp = readdir (dirp); + if (! dp) + break; + + /* Skip "", ".", and "..". "" is returned by at least one buggy + implementation: Solaris 2.4 readdir on NFS file systems. */ + entry = dp->d_name; + if (entry[entry[0] != '.' ? 0 : entry[1] != '.' ? 1 : 2] != '\0') + { + size_t entry_size = _D_EXACT_NAMLEN (dp) + 1; + if (used + entry_size < used) + xalloc_die (); + if (allocated <= used + entry_size) + { + do + { + if (2 * allocated < allocated) + xalloc_die (); + allocated *= 2; + } + while (allocated <= used + entry_size); + + name_space = xrealloc (name_space, allocated); + } + memcpy (name_space + used, entry, entry_size); + used += entry_size; + } + } + name_space[used] = '\0'; + save_errno = errno; + if (closedir (dirp) != 0) + save_errno = errno; + if (save_errno != 0) + { + free (name_space); + errno = save_errno; + return NULL; + } + return name_space; +} + +/* Return a freshly allocated string containing the file names + in directory DIR, separated by '\0' characters; + the end is marked by two '\0' characters in a row. + Return NULL (setting errno) if DIR cannot be opened, read, or closed. */ + +char * +savedir (char const *dir) +{ + return savedirstream (opendir (dir)); +} + +/* Return a freshly allocated string containing the file names + in directory FD, separated by '\0' characters; + the end is marked by two '\0' characters in a row. + Return NULL (setting errno) if FD cannot be read or closed. */ + +char * +fdsavedir (int fd) +{ + return savedirstream (fdopendir (fd)); +} diff --git a/src/bin/findutils/gnulib/lib/savedir.h b/src/bin/findutils/gnulib/lib/savedir.h new file mode 100644 index 0000000000..0c696415b8 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/savedir.h @@ -0,0 +1,26 @@ +/* Save the list of files in a directory in a string. + + Copyright (C) 1997, 1999, 2001, 2003, 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by David MacKenzie . */ + +#if !defined SAVEDIR_H_ +# define SAVEDIR_H_ + +char *savedir (char const *dir); +char *fdsavedir (int fd); + +#endif diff --git a/src/bin/findutils/gnulib/lib/stat-macros.h b/src/bin/findutils/gnulib/lib/stat-macros.h new file mode 100644 index 0000000000..690216c74e --- /dev/null +++ b/src/bin/findutils/gnulib/lib/stat-macros.h @@ -0,0 +1,3 @@ +/* All the mode bits that can be affected by chmod. */ +#define CHMOD_MODE_BITS \ + (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO) diff --git a/src/bin/findutils/gnulib/lib/stdbool.in.h b/src/bin/findutils/gnulib/lib/stdbool.in.h new file mode 100644 index 0000000000..171d70ab13 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/stdbool.in.h @@ -0,0 +1,119 @@ +/* Copyright (C) 2001, 2002, 2003, 2006, 2007 Free Software Foundation, Inc. + Written by Bruno Haible , 2001. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _GL_STDBOOL_H +#define _GL_STDBOOL_H + +/* ISO C 99 for platforms that lack it. */ + +/* Usage suggestions: + + Programs that use should be aware of some limitations + and standards compliance issues. + + Standards compliance: + + - must be #included before 'bool', 'false', 'true' + can be used. + + - You cannot assume that sizeof (bool) == 1. + + - Programs should not undefine the macros bool, true, and false, + as C99 lists that as an "obsolescent feature". + + Limitations of this substitute, when used in a C89 environment: + + - must be #included before the '_Bool' type can be used. + + - You cannot assume that _Bool is a typedef; it might be a macro. + + - Bit-fields of type 'bool' are not supported. Portable code + should use 'unsigned int foo : 1;' rather than 'bool foo : 1;'. + + - In C99, casts and automatic conversions to '_Bool' or 'bool' are + performed in such a way that every nonzero value gets converted + to 'true', and zero gets converted to 'false'. This doesn't work + with this substitute. With this substitute, only the values 0 and 1 + give the expected result when converted to _Bool' or 'bool'. + + Also, it is suggested that programs use 'bool' rather than '_Bool'; + this isn't required, but 'bool' is more common. */ + + +/* 7.16. Boolean type and values */ + +/* BeOS already #defines false 0, true 1. We use the same + definitions below, but temporarily we have to #undef them. */ +#ifdef __BEOS__ +# include /* defines bool but not _Bool */ +# undef false +# undef true +#endif + +/* For the sake of symbolic names in gdb, we define true and false as + enum constants, not only as macros. + It is tempting to write + typedef enum { false = 0, true = 1 } _Bool; + so that gdb prints values of type 'bool' symbolically. But if we do + this, values of type '_Bool' may promote to 'int' or 'unsigned int' + (see ISO C 99 6.7.2.2.(4)); however, '_Bool' must promote to 'int' + (see ISO C 99 6.3.1.1.(2)). So we add a negative value to the + enum; this ensures that '_Bool' promotes to 'int'. */ +#if defined __cplusplus || defined __BEOS__ + /* A compiler known to have 'bool'. */ + /* If the compiler already has both 'bool' and '_Bool', we can assume they + are the same types. */ +# if !@HAVE__BOOL@ +typedef bool _Bool; +# endif +#else +# if !defined __GNUC__ + /* If @HAVE__BOOL@: + Some HP-UX cc and AIX IBM C compiler versions have compiler bugs when + the built-in _Bool type is used. See + http://gcc.gnu.org/ml/gcc-patches/2003-12/msg02303.html + http://lists.gnu.org/archive/html/bug-coreutils/2005-11/msg00161.html + http://lists.gnu.org/archive/html/bug-coreutils/2005-10/msg00086.html + Similar bugs are likely with other compilers as well; this file + wouldn't be used if was working. + So we override the _Bool type. + If !@HAVE__BOOL@: + Need to define _Bool ourselves. As 'signed char' or as an enum type? + Use of a typedef, with SunPRO C, leads to a stupid + "warning: _Bool is a keyword in ISO C99". + Use of an enum type, with IRIX cc, leads to a stupid + "warning(1185): enumerated type mixed with another type". + Even the existence of an enum type, without a typedef, + "Invalid enumerator. (badenum)" with HP-UX cc on Tru64. + The only benefit of the enum, debuggability, is not important + with these compilers. So use 'signed char' and no enum. */ +# define _Bool signed char +# else + /* With this compiler, trust the _Bool type if the compiler has it. */ +# if !@HAVE__BOOL@ +typedef enum { _Bool_must_promote_to_int = -1, false = 0, true = 1 } _Bool; +# endif +# endif +#endif +#define bool _Bool + +/* The other macros must be usable in preprocessor directives. */ +#define false 0 +#define true 1 +#define __bool_true_false_are_defined 1 + +#endif /* _GL_STDBOOL_H */ diff --git a/src/bin/findutils/gnulib/lib/stdint.h b/src/bin/findutils/gnulib/lib/stdint.h new file mode 100644 index 0000000000..356f84eb1e --- /dev/null +++ b/src/bin/findutils/gnulib/lib/stdint.h @@ -0,0 +1,517 @@ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +/* Copyright (C) 2001-2002, 2004-2007 Free Software Foundation, Inc. + Written by Paul Eggert, Bruno Haible, Sam Steingold, Peter Burwood. + This file is part of gnulib. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* + * ISO C 99 for platforms that lack it. + * + */ + +#ifndef _GL_STDINT_H + +/* Get those types that are already defined in other system include + files, so that we can "#define int8_t signed char" below without + worrying about a later system include file containing a "typedef + signed char int8_t;" that will get messed up by our macro. Our + macros should all be consistent with the system versions, except + for the "fast" types and macros, which we recommend against using + in public interfaces due to compiler differences. */ + +#if 1 +# if defined __sgi && ! defined __c99 + /* Bypass IRIX's if in C89 mode, since it merely annoys users + with "This header file is to be used only for c99 mode compilations" + diagnostics. */ +# define __STDINT_H__ +# endif + /* Other systems may have an incomplete or buggy . + Include it before , since any "#include " + in would reinclude us, skipping our contents because + _GL_STDINT_H is defined. + The include_next requires a split double-inclusion guard. */ +# include_next +#endif + +#if ! defined _GL_STDINT_H && ! defined _GL_JUST_INCLUDE_SYSTEM_STDINT_H +#define _GL_STDINT_H + +/* defines some of the stdint.h types as well, on glibc, + IRIX 6.5, and OpenBSD 3.8 (via ). + AIX 5.2 isn't needed and causes troubles. + MacOS X 10.4.6 includes (which is us), but + relies on the system definitions, so include + after . */ +#if 1 && ! defined _AIX +# include +#endif + +/* Get LONG_MIN, LONG_MAX, ULONG_MAX. */ +#include + +#if 1 + /* In OpenBSD 3.8, includes , which defines + int{8,16,32,64}_t, uint{8,16,32,64}_t and __BIT_TYPES_DEFINED__. + also defines intptr_t and uintptr_t. */ +# define _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H +# include +# undef _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H +#elif 0 + /* Solaris 7 has the types except the *_fast*_t types, and + the macros except for *_FAST*_*, INTPTR_MIN, PTRDIFF_MIN, PTRDIFF_MAX. */ +# include +#endif + +#if 0 && ! defined __BIT_TYPES_DEFINED__ + /* Linux libc4 >= 4.6.7 and libc5 have a that defines + int{8,16,32,64}_t and __BIT_TYPES_DEFINED__. In libc5 >= 5.2.2 it is + included by . */ +# include +#endif + +#if ! defined __cplusplus || defined __STDC_CONSTANT_MACROS + +/* Get WCHAR_MIN, WCHAR_MAX. */ +# if ! (defined WCHAR_MIN && defined WCHAR_MAX) +# include +# endif + +#endif + +/* Minimum and maximum values for a integer type under the usual assumption. + Return an unspecified value if BITS == 0, adding a check to pacify + picky compilers. */ + +#define _STDINT_MIN(signed, bits, zero) \ + ((signed) ? (- ((zero) + 1) << ((bits) ? (bits) - 1 : 0)) : (zero)) + +#define _STDINT_MAX(signed, bits, zero) \ + ((signed) \ + ? ~ _STDINT_MIN (signed, bits, zero) \ + : /* The expression for the unsigned case. The subtraction of (signed) \ + is a nop in the unsigned case and avoids "signed integer overflow" \ + warnings in the signed case. */ \ + ((((zero) + 1) << ((bits) ? (bits) - 1 - (signed) : 0)) - 1) * 2 + 1) + +/* 7.18.1.1. Exact-width integer types */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits. */ + +#undef int8_t +#undef uint8_t +#define int8_t signed char +#define uint8_t unsigned char + +#undef int16_t +#undef uint16_t +#define int16_t short int +#define uint16_t unsigned short int + +#undef int32_t +#undef uint32_t +#define int32_t int +#define uint32_t unsigned int + +/* Do not undefine int64_t if gnulib is not being used with 64-bit + types, since otherwise it breaks platforms like Tandem/NSK. */ +#if LONG_MAX >> 31 >> 31 == 1 +# undef int64_t +# define int64_t long int +# define GL_INT64_T +#elif defined _MSC_VER +# undef int64_t +# define int64_t __int64 +# define GL_INT64_T +#elif 1 +# undef int64_t +# define int64_t long long int +# define GL_INT64_T +#endif + +#if ULONG_MAX >> 31 >> 31 >> 1 == 1 +# undef uint64_t +# define uint64_t unsigned long int +# define GL_UINT64_T +#elif defined _MSC_VER +# undef uint64_t +# define uint64_t unsigned __int64 +# define GL_UINT64_T +#elif 1 +# undef uint64_t +# define uint64_t unsigned long long int +# define GL_UINT64_T +#endif + +/* Avoid collision with Solaris 2.5.1 etc. */ +#define _UINT8_T +#define _UINT32_T +#define _UINT64_T + + +/* 7.18.1.2. Minimum-width integer types */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits. Therefore the leastN_t types + are the same as the corresponding N_t types. */ + +#undef int_least8_t +#undef uint_least8_t +#undef int_least16_t +#undef uint_least16_t +#undef int_least32_t +#undef uint_least32_t +#undef int_least64_t +#undef uint_least64_t +#define int_least8_t int8_t +#define uint_least8_t uint8_t +#define int_least16_t int16_t +#define uint_least16_t uint16_t +#define int_least32_t int32_t +#define uint_least32_t uint32_t +#ifdef GL_INT64_T +# define int_least64_t int64_t +#endif +#ifdef GL_UINT64_T +# define uint_least64_t uint64_t +#endif + +/* 7.18.1.3. Fastest minimum-width integer types */ + +/* Note: Other substitutes may define these types differently. + It is not recommended to use these types in public header files. */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits. Therefore the fastN_t types + are taken from the same list of types. Assume that 'long int' + is fast enough for all narrower integers. */ + +#undef int_fast8_t +#undef uint_fast8_t +#undef int_fast16_t +#undef uint_fast16_t +#undef int_fast32_t +#undef uint_fast32_t +#undef int_fast64_t +#undef uint_fast64_t +#define int_fast8_t long int +#define uint_fast8_t unsigned int_fast8_t +#define int_fast16_t long int +#define uint_fast16_t unsigned int_fast16_t +#define int_fast32_t long int +#define uint_fast32_t unsigned int_fast32_t +#ifdef GL_INT64_T +# define int_fast64_t int64_t +#endif +#ifdef GL_UINT64_T +# define uint_fast64_t uint64_t +#endif + +/* 7.18.1.4. Integer types capable of holding object pointers */ + +#undef intptr_t +#undef uintptr_t +#define intptr_t long int +#define uintptr_t unsigned long int + +/* 7.18.1.5. Greatest-width integer types */ + +/* Note: These types are compiler dependent. It may be unwise to use them in + public header files. */ + +#undef intmax_t +#if 1 && LONG_MAX >> 30 == 1 +# define intmax_t long long int +#elif defined GL_INT64_T +# define intmax_t int64_t +#else +# define intmax_t long int +#endif + +#undef uintmax_t +#if 1 && ULONG_MAX >> 31 == 1 +# define uintmax_t unsigned long long int +#elif defined GL_UINT64_T +# define uintmax_t uint64_t +#else +# define uintmax_t unsigned long int +#endif + +/* Verify that intmax_t and uintmax_t have the same size. Too much code + breaks if this is not the case. If this check fails, the reason is likely + to be found in the autoconf macros. */ +typedef int _verify_intmax_size[2 * (sizeof (intmax_t) == sizeof (uintmax_t)) - 1]; + +/* 7.18.2. Limits of specified-width integer types */ + +#if ! defined __cplusplus || defined __STDC_LIMIT_MACROS + +/* 7.18.2.1. Limits of exact-width integer types */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits. */ + +#undef INT8_MIN +#undef INT8_MAX +#undef UINT8_MAX +#define INT8_MIN (~ INT8_MAX) +#define INT8_MAX 127 +#define UINT8_MAX 255 + +#undef INT16_MIN +#undef INT16_MAX +#undef UINT16_MAX +#define INT16_MIN (~ INT16_MAX) +#define INT16_MAX 32767 +#define UINT16_MAX 65535 + +#undef INT32_MIN +#undef INT32_MAX +#undef UINT32_MAX +#define INT32_MIN (~ INT32_MAX) +#define INT32_MAX 2147483647 +#define UINT32_MAX 4294967295U + +#undef INT64_MIN +#undef INT64_MAX +#ifdef GL_INT64_T +/* Prefer (- INTMAX_C (1) << 63) over (~ INT64_MAX) because SunPRO C 5.0 + evaluates the latter incorrectly in preprocessor expressions. */ +# define INT64_MIN (- INTMAX_C (1) << 63) +# define INT64_MAX INTMAX_C (9223372036854775807) +#endif + +#undef UINT64_MAX +#ifdef GL_UINT64_T +# define UINT64_MAX UINTMAX_C (18446744073709551615) +#endif + +/* 7.18.2.2. Limits of minimum-width integer types */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits. Therefore the leastN_t types + are the same as the corresponding N_t types. */ + +#undef INT_LEAST8_MIN +#undef INT_LEAST8_MAX +#undef UINT_LEAST8_MAX +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST8_MAX INT8_MAX +#define UINT_LEAST8_MAX UINT8_MAX + +#undef INT_LEAST16_MIN +#undef INT_LEAST16_MAX +#undef UINT_LEAST16_MAX +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST16_MAX INT16_MAX +#define UINT_LEAST16_MAX UINT16_MAX + +#undef INT_LEAST32_MIN +#undef INT_LEAST32_MAX +#undef UINT_LEAST32_MAX +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST32_MAX INT32_MAX +#define UINT_LEAST32_MAX UINT32_MAX + +#undef INT_LEAST64_MIN +#undef INT_LEAST64_MAX +#ifdef GL_INT64_T +# define INT_LEAST64_MIN INT64_MIN +# define INT_LEAST64_MAX INT64_MAX +#endif + +#undef UINT_LEAST64_MAX +#ifdef GL_UINT64_T +# define UINT_LEAST64_MAX UINT64_MAX +#endif + +/* 7.18.2.3. Limits of fastest minimum-width integer types */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits. Therefore the fastN_t types + are taken from the same list of types. */ + +#undef INT_FAST8_MIN +#undef INT_FAST8_MAX +#undef UINT_FAST8_MAX +#define INT_FAST8_MIN LONG_MIN +#define INT_FAST8_MAX LONG_MAX +#define UINT_FAST8_MAX ULONG_MAX + +#undef INT_FAST16_MIN +#undef INT_FAST16_MAX +#undef UINT_FAST16_MAX +#define INT_FAST16_MIN LONG_MIN +#define INT_FAST16_MAX LONG_MAX +#define UINT_FAST16_MAX ULONG_MAX + +#undef INT_FAST32_MIN +#undef INT_FAST32_MAX +#undef UINT_FAST32_MAX +#define INT_FAST32_MIN LONG_MIN +#define INT_FAST32_MAX LONG_MAX +#define UINT_FAST32_MAX ULONG_MAX + +#undef INT_FAST64_MIN +#undef INT_FAST64_MAX +#ifdef GL_INT64_T +# define INT_FAST64_MIN INT64_MIN +# define INT_FAST64_MAX INT64_MAX +#endif + +#undef UINT_FAST64_MAX +#ifdef GL_UINT64_T +# define UINT_FAST64_MAX UINT64_MAX +#endif + +/* 7.18.2.4. Limits of integer types capable of holding object pointers */ + +#undef INTPTR_MIN +#undef INTPTR_MAX +#undef UINTPTR_MAX +#define INTPTR_MIN LONG_MIN +#define INTPTR_MAX LONG_MAX +#define UINTPTR_MAX ULONG_MAX + +/* 7.18.2.5. Limits of greatest-width integer types */ + +#undef INTMAX_MIN +#undef INTMAX_MAX +#ifdef INT64_MAX +# define INTMAX_MIN INT64_MIN +# define INTMAX_MAX INT64_MAX +#else +# define INTMAX_MIN INT32_MIN +# define INTMAX_MAX INT32_MAX +#endif + +#undef UINTMAX_MAX +#ifdef UINT64_MAX +# define UINTMAX_MAX UINT64_MAX +#else +# define UINTMAX_MAX UINT32_MAX +#endif + +/* 7.18.3. Limits of other integer types */ + +/* ptrdiff_t limits */ +#undef PTRDIFF_MIN +#undef PTRDIFF_MAX +#define PTRDIFF_MIN \ + _STDINT_MIN (1, 32, 0l) +#define PTRDIFF_MAX \ + _STDINT_MAX (1, 32, 0l) + +/* sig_atomic_t limits */ +#undef SIG_ATOMIC_MIN +#undef SIG_ATOMIC_MAX +#define SIG_ATOMIC_MIN \ + _STDINT_MIN (1, 32, \ + 0) +#define SIG_ATOMIC_MAX \ + _STDINT_MAX (1, 32, \ + 0) + + +/* size_t limit */ +#undef SIZE_MAX +#define SIZE_MAX _STDINT_MAX (0, 32, 0ul) + +/* wchar_t limits */ +#undef WCHAR_MIN +#undef WCHAR_MAX +#define WCHAR_MIN \ + _STDINT_MIN (0, 16, 0) +#define WCHAR_MAX \ + _STDINT_MAX (0, 16, 0) + +/* wint_t limits */ +#undef WINT_MIN +#undef WINT_MAX +#define WINT_MIN \ + _STDINT_MIN (0, 32, 0u) +#define WINT_MAX \ + _STDINT_MAX (0, 32, 0u) + +#endif /* !defined __cplusplus || defined __STDC_LIMIT_MACROS */ + +/* 7.18.4. Macros for integer constants */ + +#if ! defined __cplusplus || defined __STDC_CONSTANT_MACROS + +/* 7.18.4.1. Macros for minimum-width integer constants */ +/* According to ISO C 99 Technical Corrigendum 1 */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits, and int is 32 bits. */ + +#undef INT8_C +#undef UINT8_C +#define INT8_C(x) x +#define UINT8_C(x) x + +#undef INT16_C +#undef UINT16_C +#define INT16_C(x) x +#define UINT16_C(x) x + +#undef INT32_C +#undef UINT32_C +#define INT32_C(x) x +#define UINT32_C(x) x ## U + +#undef INT64_C +#undef UINT64_C +#if LONG_MAX >> 31 >> 31 == 1 +# define INT64_C(x) x##L +#elif defined _MSC_VER +# define INT64_C(x) x##i64 +#elif 1 +# define INT64_C(x) x##LL +#endif +#if ULONG_MAX >> 31 >> 31 >> 1 == 1 +# define UINT64_C(x) x##UL +#elif defined _MSC_VER +# define UINT64_C(x) x##ui64 +#elif 1 +# define UINT64_C(x) x##ULL +#endif + +/* 7.18.4.2. Macros for greatest-width integer constants */ + +#undef INTMAX_C +#if 1 && LONG_MAX >> 30 == 1 +# define INTMAX_C(x) x##LL +#elif defined GL_INT64_T +# define INTMAX_C(x) INT64_C(x) +#else +# define INTMAX_C(x) x##L +#endif + +#undef UINTMAX_C +#if 1 && ULONG_MAX >> 31 == 1 +# define UINTMAX_C(x) x##ULL +#elif defined GL_UINT64_T +# define UINTMAX_C(x) UINT64_C(x) +#else +# define UINTMAX_C(x) x##UL +#endif + +#endif /* !defined __cplusplus || defined __STDC_CONSTANT_MACROS */ + +#endif /* _GL_STDINT_H */ +#endif /* !defined _GL_STDINT_H && !defined _GL_JUST_INCLUDE_SYSTEM_STDINT_H */ diff --git a/src/bin/findutils/gnulib/lib/stdint.in.h b/src/bin/findutils/gnulib/lib/stdint.in.h new file mode 100644 index 0000000000..8aee8682b4 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/stdint.in.h @@ -0,0 +1,516 @@ +/* Copyright (C) 2001-2002, 2004-2007 Free Software Foundation, Inc. + Written by Paul Eggert, Bruno Haible, Sam Steingold, Peter Burwood. + This file is part of gnulib. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* + * ISO C 99 for platforms that lack it. + * + */ + +#ifndef _GL_STDINT_H + +/* Get those types that are already defined in other system include + files, so that we can "#define int8_t signed char" below without + worrying about a later system include file containing a "typedef + signed char int8_t;" that will get messed up by our macro. Our + macros should all be consistent with the system versions, except + for the "fast" types and macros, which we recommend against using + in public interfaces due to compiler differences. */ + +#if @HAVE_STDINT_H@ +# if defined __sgi && ! defined __c99 + /* Bypass IRIX's if in C89 mode, since it merely annoys users + with "This header file is to be used only for c99 mode compilations" + diagnostics. */ +# define __STDINT_H__ +# endif + /* Other systems may have an incomplete or buggy . + Include it before , since any "#include " + in would reinclude us, skipping our contents because + _GL_STDINT_H is defined. + The include_next requires a split double-inclusion guard. */ +# @INCLUDE_NEXT@ @NEXT_STDINT_H@ +#endif + +#if ! defined _GL_STDINT_H && ! defined _GL_JUST_INCLUDE_SYSTEM_STDINT_H +#define _GL_STDINT_H + +/* defines some of the stdint.h types as well, on glibc, + IRIX 6.5, and OpenBSD 3.8 (via ). + AIX 5.2 isn't needed and causes troubles. + MacOS X 10.4.6 includes (which is us), but + relies on the system definitions, so include + after @NEXT_STDINT_H@. */ +#if @HAVE_SYS_TYPES_H@ && ! defined _AIX +# include +#endif + +/* Get LONG_MIN, LONG_MAX, ULONG_MAX. */ +#include + +#if @HAVE_INTTYPES_H@ + /* In OpenBSD 3.8, includes , which defines + int{8,16,32,64}_t, uint{8,16,32,64}_t and __BIT_TYPES_DEFINED__. + also defines intptr_t and uintptr_t. */ +# define _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H +# include +# undef _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H +#elif @HAVE_SYS_INTTYPES_H@ + /* Solaris 7 has the types except the *_fast*_t types, and + the macros except for *_FAST*_*, INTPTR_MIN, PTRDIFF_MIN, PTRDIFF_MAX. */ +# include +#endif + +#if @HAVE_SYS_BITYPES_H@ && ! defined __BIT_TYPES_DEFINED__ + /* Linux libc4 >= 4.6.7 and libc5 have a that defines + int{8,16,32,64}_t and __BIT_TYPES_DEFINED__. In libc5 >= 5.2.2 it is + included by . */ +# include +#endif + +#if ! defined __cplusplus || defined __STDC_CONSTANT_MACROS + +/* Get WCHAR_MIN, WCHAR_MAX. */ +# if ! (defined WCHAR_MIN && defined WCHAR_MAX) +# include +# endif + +#endif + +/* Minimum and maximum values for a integer type under the usual assumption. + Return an unspecified value if BITS == 0, adding a check to pacify + picky compilers. */ + +#define _STDINT_MIN(signed, bits, zero) \ + ((signed) ? (- ((zero) + 1) << ((bits) ? (bits) - 1 : 0)) : (zero)) + +#define _STDINT_MAX(signed, bits, zero) \ + ((signed) \ + ? ~ _STDINT_MIN (signed, bits, zero) \ + : /* The expression for the unsigned case. The subtraction of (signed) \ + is a nop in the unsigned case and avoids "signed integer overflow" \ + warnings in the signed case. */ \ + ((((zero) + 1) << ((bits) ? (bits) - 1 - (signed) : 0)) - 1) * 2 + 1) + +/* 7.18.1.1. Exact-width integer types */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits. */ + +#undef int8_t +#undef uint8_t +#define int8_t signed char +#define uint8_t unsigned char + +#undef int16_t +#undef uint16_t +#define int16_t short int +#define uint16_t unsigned short int + +#undef int32_t +#undef uint32_t +#define int32_t int +#define uint32_t unsigned int + +/* Do not undefine int64_t if gnulib is not being used with 64-bit + types, since otherwise it breaks platforms like Tandem/NSK. */ +#if LONG_MAX >> 31 >> 31 == 1 +# undef int64_t +# define int64_t long int +# define GL_INT64_T +#elif defined _MSC_VER +# undef int64_t +# define int64_t __int64 +# define GL_INT64_T +#elif @HAVE_LONG_LONG_INT@ +# undef int64_t +# define int64_t long long int +# define GL_INT64_T +#endif + +#if ULONG_MAX >> 31 >> 31 >> 1 == 1 +# undef uint64_t +# define uint64_t unsigned long int +# define GL_UINT64_T +#elif defined _MSC_VER +# undef uint64_t +# define uint64_t unsigned __int64 +# define GL_UINT64_T +#elif @HAVE_UNSIGNED_LONG_LONG_INT@ +# undef uint64_t +# define uint64_t unsigned long long int +# define GL_UINT64_T +#endif + +/* Avoid collision with Solaris 2.5.1 etc. */ +#define _UINT8_T +#define _UINT32_T +#define _UINT64_T + + +/* 7.18.1.2. Minimum-width integer types */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits. Therefore the leastN_t types + are the same as the corresponding N_t types. */ + +#undef int_least8_t +#undef uint_least8_t +#undef int_least16_t +#undef uint_least16_t +#undef int_least32_t +#undef uint_least32_t +#undef int_least64_t +#undef uint_least64_t +#define int_least8_t int8_t +#define uint_least8_t uint8_t +#define int_least16_t int16_t +#define uint_least16_t uint16_t +#define int_least32_t int32_t +#define uint_least32_t uint32_t +#ifdef GL_INT64_T +# define int_least64_t int64_t +#endif +#ifdef GL_UINT64_T +# define uint_least64_t uint64_t +#endif + +/* 7.18.1.3. Fastest minimum-width integer types */ + +/* Note: Other substitutes may define these types differently. + It is not recommended to use these types in public header files. */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits. Therefore the fastN_t types + are taken from the same list of types. Assume that 'long int' + is fast enough for all narrower integers. */ + +#undef int_fast8_t +#undef uint_fast8_t +#undef int_fast16_t +#undef uint_fast16_t +#undef int_fast32_t +#undef uint_fast32_t +#undef int_fast64_t +#undef uint_fast64_t +#define int_fast8_t long int +#define uint_fast8_t unsigned int_fast8_t +#define int_fast16_t long int +#define uint_fast16_t unsigned int_fast16_t +#define int_fast32_t long int +#define uint_fast32_t unsigned int_fast32_t +#ifdef GL_INT64_T +# define int_fast64_t int64_t +#endif +#ifdef GL_UINT64_T +# define uint_fast64_t uint64_t +#endif + +/* 7.18.1.4. Integer types capable of holding object pointers */ + +#undef intptr_t +#undef uintptr_t +#define intptr_t long int +#define uintptr_t unsigned long int + +/* 7.18.1.5. Greatest-width integer types */ + +/* Note: These types are compiler dependent. It may be unwise to use them in + public header files. */ + +#undef intmax_t +#if @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1 +# define intmax_t long long int +#elif defined GL_INT64_T +# define intmax_t int64_t +#else +# define intmax_t long int +#endif + +#undef uintmax_t +#if @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1 +# define uintmax_t unsigned long long int +#elif defined GL_UINT64_T +# define uintmax_t uint64_t +#else +# define uintmax_t unsigned long int +#endif + +/* Verify that intmax_t and uintmax_t have the same size. Too much code + breaks if this is not the case. If this check fails, the reason is likely + to be found in the autoconf macros. */ +typedef int _verify_intmax_size[2 * (sizeof (intmax_t) == sizeof (uintmax_t)) - 1]; + +/* 7.18.2. Limits of specified-width integer types */ + +#if ! defined __cplusplus || defined __STDC_LIMIT_MACROS + +/* 7.18.2.1. Limits of exact-width integer types */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits. */ + +#undef INT8_MIN +#undef INT8_MAX +#undef UINT8_MAX +#define INT8_MIN (~ INT8_MAX) +#define INT8_MAX 127 +#define UINT8_MAX 255 + +#undef INT16_MIN +#undef INT16_MAX +#undef UINT16_MAX +#define INT16_MIN (~ INT16_MAX) +#define INT16_MAX 32767 +#define UINT16_MAX 65535 + +#undef INT32_MIN +#undef INT32_MAX +#undef UINT32_MAX +#define INT32_MIN (~ INT32_MAX) +#define INT32_MAX 2147483647 +#define UINT32_MAX 4294967295U + +#undef INT64_MIN +#undef INT64_MAX +#ifdef GL_INT64_T +/* Prefer (- INTMAX_C (1) << 63) over (~ INT64_MAX) because SunPRO C 5.0 + evaluates the latter incorrectly in preprocessor expressions. */ +# define INT64_MIN (- INTMAX_C (1) << 63) +# define INT64_MAX INTMAX_C (9223372036854775807) +#endif + +#undef UINT64_MAX +#ifdef GL_UINT64_T +# define UINT64_MAX UINTMAX_C (18446744073709551615) +#endif + +/* 7.18.2.2. Limits of minimum-width integer types */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits. Therefore the leastN_t types + are the same as the corresponding N_t types. */ + +#undef INT_LEAST8_MIN +#undef INT_LEAST8_MAX +#undef UINT_LEAST8_MAX +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST8_MAX INT8_MAX +#define UINT_LEAST8_MAX UINT8_MAX + +#undef INT_LEAST16_MIN +#undef INT_LEAST16_MAX +#undef UINT_LEAST16_MAX +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST16_MAX INT16_MAX +#define UINT_LEAST16_MAX UINT16_MAX + +#undef INT_LEAST32_MIN +#undef INT_LEAST32_MAX +#undef UINT_LEAST32_MAX +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST32_MAX INT32_MAX +#define UINT_LEAST32_MAX UINT32_MAX + +#undef INT_LEAST64_MIN +#undef INT_LEAST64_MAX +#ifdef GL_INT64_T +# define INT_LEAST64_MIN INT64_MIN +# define INT_LEAST64_MAX INT64_MAX +#endif + +#undef UINT_LEAST64_MAX +#ifdef GL_UINT64_T +# define UINT_LEAST64_MAX UINT64_MAX +#endif + +/* 7.18.2.3. Limits of fastest minimum-width integer types */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits. Therefore the fastN_t types + are taken from the same list of types. */ + +#undef INT_FAST8_MIN +#undef INT_FAST8_MAX +#undef UINT_FAST8_MAX +#define INT_FAST8_MIN LONG_MIN +#define INT_FAST8_MAX LONG_MAX +#define UINT_FAST8_MAX ULONG_MAX + +#undef INT_FAST16_MIN +#undef INT_FAST16_MAX +#undef UINT_FAST16_MAX +#define INT_FAST16_MIN LONG_MIN +#define INT_FAST16_MAX LONG_MAX +#define UINT_FAST16_MAX ULONG_MAX + +#undef INT_FAST32_MIN +#undef INT_FAST32_MAX +#undef UINT_FAST32_MAX +#define INT_FAST32_MIN LONG_MIN +#define INT_FAST32_MAX LONG_MAX +#define UINT_FAST32_MAX ULONG_MAX + +#undef INT_FAST64_MIN +#undef INT_FAST64_MAX +#ifdef GL_INT64_T +# define INT_FAST64_MIN INT64_MIN +# define INT_FAST64_MAX INT64_MAX +#endif + +#undef UINT_FAST64_MAX +#ifdef GL_UINT64_T +# define UINT_FAST64_MAX UINT64_MAX +#endif + +/* 7.18.2.4. Limits of integer types capable of holding object pointers */ + +#undef INTPTR_MIN +#undef INTPTR_MAX +#undef UINTPTR_MAX +#define INTPTR_MIN LONG_MIN +#define INTPTR_MAX LONG_MAX +#define UINTPTR_MAX ULONG_MAX + +/* 7.18.2.5. Limits of greatest-width integer types */ + +#undef INTMAX_MIN +#undef INTMAX_MAX +#ifdef INT64_MAX +# define INTMAX_MIN INT64_MIN +# define INTMAX_MAX INT64_MAX +#else +# define INTMAX_MIN INT32_MIN +# define INTMAX_MAX INT32_MAX +#endif + +#undef UINTMAX_MAX +#ifdef UINT64_MAX +# define UINTMAX_MAX UINT64_MAX +#else +# define UINTMAX_MAX UINT32_MAX +#endif + +/* 7.18.3. Limits of other integer types */ + +/* ptrdiff_t limits */ +#undef PTRDIFF_MIN +#undef PTRDIFF_MAX +#define PTRDIFF_MIN \ + _STDINT_MIN (1, @BITSIZEOF_PTRDIFF_T@, 0@PTRDIFF_T_SUFFIX@) +#define PTRDIFF_MAX \ + _STDINT_MAX (1, @BITSIZEOF_PTRDIFF_T@, 0@PTRDIFF_T_SUFFIX@) + +/* sig_atomic_t limits */ +#undef SIG_ATOMIC_MIN +#undef SIG_ATOMIC_MAX +#define SIG_ATOMIC_MIN \ + _STDINT_MIN (@HAVE_SIGNED_SIG_ATOMIC_T@, @BITSIZEOF_SIG_ATOMIC_T@, \ + 0@SIG_ATOMIC_T_SUFFIX@) +#define SIG_ATOMIC_MAX \ + _STDINT_MAX (@HAVE_SIGNED_SIG_ATOMIC_T@, @BITSIZEOF_SIG_ATOMIC_T@, \ + 0@SIG_ATOMIC_T_SUFFIX@) + + +/* size_t limit */ +#undef SIZE_MAX +#define SIZE_MAX _STDINT_MAX (0, @BITSIZEOF_SIZE_T@, 0@SIZE_T_SUFFIX@) + +/* wchar_t limits */ +#undef WCHAR_MIN +#undef WCHAR_MAX +#define WCHAR_MIN \ + _STDINT_MIN (@HAVE_SIGNED_WCHAR_T@, @BITSIZEOF_WCHAR_T@, 0@WCHAR_T_SUFFIX@) +#define WCHAR_MAX \ + _STDINT_MAX (@HAVE_SIGNED_WCHAR_T@, @BITSIZEOF_WCHAR_T@, 0@WCHAR_T_SUFFIX@) + +/* wint_t limits */ +#undef WINT_MIN +#undef WINT_MAX +#define WINT_MIN \ + _STDINT_MIN (@HAVE_SIGNED_WINT_T@, @BITSIZEOF_WINT_T@, 0@WINT_T_SUFFIX@) +#define WINT_MAX \ + _STDINT_MAX (@HAVE_SIGNED_WINT_T@, @BITSIZEOF_WINT_T@, 0@WINT_T_SUFFIX@) + +#endif /* !defined __cplusplus || defined __STDC_LIMIT_MACROS */ + +/* 7.18.4. Macros for integer constants */ + +#if ! defined __cplusplus || defined __STDC_CONSTANT_MACROS + +/* 7.18.4.1. Macros for minimum-width integer constants */ +/* According to ISO C 99 Technical Corrigendum 1 */ + +/* Here we assume a standard architecture where the hardware integer + types have 8, 16, 32, optionally 64 bits, and int is 32 bits. */ + +#undef INT8_C +#undef UINT8_C +#define INT8_C(x) x +#define UINT8_C(x) x + +#undef INT16_C +#undef UINT16_C +#define INT16_C(x) x +#define UINT16_C(x) x + +#undef INT32_C +#undef UINT32_C +#define INT32_C(x) x +#define UINT32_C(x) x ## U + +#undef INT64_C +#undef UINT64_C +#if LONG_MAX >> 31 >> 31 == 1 +# define INT64_C(x) x##L +#elif defined _MSC_VER +# define INT64_C(x) x##i64 +#elif @HAVE_LONG_LONG_INT@ +# define INT64_C(x) x##LL +#endif +#if ULONG_MAX >> 31 >> 31 >> 1 == 1 +# define UINT64_C(x) x##UL +#elif defined _MSC_VER +# define UINT64_C(x) x##ui64 +#elif @HAVE_UNSIGNED_LONG_LONG_INT@ +# define UINT64_C(x) x##ULL +#endif + +/* 7.18.4.2. Macros for greatest-width integer constants */ + +#undef INTMAX_C +#if @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1 +# define INTMAX_C(x) x##LL +#elif defined GL_INT64_T +# define INTMAX_C(x) INT64_C(x) +#else +# define INTMAX_C(x) x##L +#endif + +#undef UINTMAX_C +#if @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1 +# define UINTMAX_C(x) x##ULL +#elif defined GL_UINT64_T +# define UINTMAX_C(x) UINT64_C(x) +#else +# define UINTMAX_C(x) x##UL +#endif + +#endif /* !defined __cplusplus || defined __STDC_CONSTANT_MACROS */ + +#endif /* _GL_STDINT_H */ +#endif /* !defined _GL_STDINT_H && !defined _GL_JUST_INCLUDE_SYSTEM_STDINT_H */ diff --git a/src/bin/findutils/gnulib/lib/stdio--.h b/src/bin/findutils/gnulib/lib/stdio--.h new file mode 100644 index 0000000000..39fca29200 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/stdio--.h @@ -0,0 +1,27 @@ +/* Like stdio.h, but redefine some names to avoid glitches. + + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert. */ + +#include +#include "stdio-safer.h" + +#undef fopen +#define fopen fopen_safer + +#undef tmpfile +#define tmpfile tmpfile_safer diff --git a/src/bin/findutils/gnulib/lib/stdio-safer.h b/src/bin/findutils/gnulib/lib/stdio-safer.h new file mode 100644 index 0000000000..c881d5a6a6 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/stdio-safer.h @@ -0,0 +1,23 @@ +/* Invoke stdio functions, but avoid some glitches. + + Copyright (C) 2001, 2003, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert. */ + +#include + +FILE *fopen_safer (char const *, char const *); +FILE *tmpfile_safer (void); diff --git a/src/bin/findutils/gnulib/lib/stdio.h b/src/bin/findutils/gnulib/lib/stdio.h new file mode 100644 index 0000000000..2479609407 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/stdio.h @@ -0,0 +1,411 @@ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +/* A GNU-like . + + Copyright (C) 2004, 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#if defined __need_FILE || defined __need___FILE +/* Special invocation convention inside glibc header files. */ + +#include_next + +#else +/* Normal invocation convention. */ + +#ifndef _GL_STDIO_H + +/* The include_next requires a split double-inclusion guard. */ +#include_next + +#ifndef _GL_STDIO_H +#define _GL_STDIO_H + +#include +#include + +#if (1 && 0) \ + || (1 && 0) \ + || (1 && !0) \ + || (1 && (!0 || 0)) +/* Get off_t and ssize_t. */ +# include +#endif + +#ifndef __attribute__ +/* This feature is available in gcc versions 2.5 and later. */ +# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__ +# define __attribute__(Spec) /* empty */ +# endif +/* The __-protected variants of `format' and `printf' attributes + are accepted by gcc versions 2.6.4 (effectively 2.7) and later. */ +# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7) +# define __format__ format +# define __printf__ printf +# endif +#endif + + +/* The definition of GL_LINK_WARNING is copied here. */ +/* GL_LINK_WARNING("literal string") arranges to emit the literal string as + a linker warning on most glibc systems. + We use a linker warning rather than a preprocessor warning, because + #warning cannot be used inside macros. */ +#ifndef GL_LINK_WARNING + /* This works on platforms with GNU ld and ELF object format. + Testing __GLIBC__ is sufficient for asserting that GNU ld is in use. + Testing __ELF__ guarantees the ELF object format. + Testing __GNUC__ is necessary for the compound expression syntax. */ +# if defined __GLIBC__ && defined __ELF__ && defined __GNUC__ +# define GL_LINK_WARNING(message) \ + GL_LINK_WARNING1 (__FILE__, __LINE__, message) +# define GL_LINK_WARNING1(file, line, message) \ + GL_LINK_WARNING2 (file, line, message) /* macroexpand file and line */ +# define GL_LINK_WARNING2(file, line, message) \ + GL_LINK_WARNING3 (file ":" #line ": warning: " message) +# define GL_LINK_WARNING3(message) \ + ({ static const char warning[sizeof (message)] \ + __attribute__ ((__unused__, \ + __section__ (".gnu.warning"), \ + __aligned__ (1))) \ + = message "\n"; \ + (void)0; \ + }) +# else +# define GL_LINK_WARNING(message) ((void) 0) +# endif +#endif + + +#ifdef __cplusplus +extern "C" { +#endif + + +#if 0 +# if 0 +# define fprintf rpl_fprintf +extern int fprintf (FILE *fp, const char *format, ...) + __attribute__ ((__format__ (__printf__, 2, 3))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef fprintf +# define fprintf \ + (GL_LINK_WARNING ("fprintf is not always POSIX compliant - " \ + "use gnulib module fprintf-posix for portable " \ + "POSIX compliance"), \ + fprintf) +#endif + +#if 0 +# if 0 +# define vfprintf rpl_vfprintf +extern int vfprintf (FILE *fp, const char *format, va_list args) + __attribute__ ((__format__ (__printf__, 2, 0))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef vfprintf +# define vfprintf(s,f,a) \ + (GL_LINK_WARNING ("vfprintf is not always POSIX compliant - " \ + "use gnulib module vfprintf-posix for portable " \ + "POSIX compliance"), \ + vfprintf (s, f, a)) +#endif + +#if 0 +# if 0 +/* Don't break __attribute__((format(printf,M,N))). */ +# define printf __printf__ +extern int printf (const char *format, ...) + __attribute__ ((__format__ (__printf__, 1, 2))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef printf +# define printf \ + (GL_LINK_WARNING ("printf is not always POSIX compliant - " \ + "use gnulib module printf-posix for portable " \ + "POSIX compliance"), \ + printf) +/* Don't break __attribute__((format(printf,M,N))). */ +# define format(kind,m,n) format (__##kind##__, m, n) +# define __format__(kind,m,n) __format__ (__##kind##__, m, n) +# define ____printf____ __printf__ +# define ____scanf____ __scanf__ +# define ____strftime____ __strftime__ +# define ____strfmon____ __strfmon__ +#endif + +#if 0 +# if 0 +# define vprintf rpl_vprintf +extern int vprintf (const char *format, va_list args) + __attribute__ ((__format__ (__printf__, 1, 0))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef vprintf +# define vprintf(f,a) \ + (GL_LINK_WARNING ("vprintf is not always POSIX compliant - " \ + "use gnulib module vprintf-posix for portable " \ + "POSIX compliance"), \ + vprintf (f, a)) +#endif + +#if 0 +# if 0 +# define snprintf rpl_snprintf +# endif +# if 0 || !1 +extern int snprintf (char *str, size_t size, const char *format, ...) + __attribute__ ((__format__ (__printf__, 3, 4))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef snprintf +# define snprintf \ + (GL_LINK_WARNING ("snprintf is unportable - " \ + "use gnulib module snprintf for portability"), \ + snprintf) +#endif + +#if 0 +# if 0 +# define vsnprintf rpl_vsnprintf +# endif +# if 0 || !1 +extern int vsnprintf (char *str, size_t size, const char *format, va_list args) + __attribute__ ((__format__ (__printf__, 3, 0))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef vsnprintf +# define vsnprintf(b,s,f,a) \ + (GL_LINK_WARNING ("vsnprintf is unportable - " \ + "use gnulib module vsnprintf for portability"), \ + vsnprintf (b, s, f, a)) +#endif + +#if 0 +# if 0 +# define sprintf rpl_sprintf +extern int sprintf (char *str, const char *format, ...) + __attribute__ ((__format__ (__printf__, 2, 3))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef sprintf +# define sprintf \ + (GL_LINK_WARNING ("sprintf is not always POSIX compliant - " \ + "use gnulib module sprintf-posix for portable " \ + "POSIX compliance"), \ + sprintf) +#endif + +#if 0 +# if 0 +# define vsprintf rpl_vsprintf +extern int vsprintf (char *str, const char *format, va_list args) + __attribute__ ((__format__ (__printf__, 2, 0))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef vsprintf +# define vsprintf(b,f,a) \ + (GL_LINK_WARNING ("vsprintf is not always POSIX compliant - " \ + "use gnulib module vsprintf-posix for portable " \ + "POSIX compliance"), \ + vsprintf (b, f, a)) +#endif + +#if 0 +# if 0 +# define asprintf rpl_asprintf +# define vasprintf rpl_vasprintf +# endif +# if 0 || !1 + /* Write formatted output to a string dynamically allocated with malloc(). + If the memory allocation succeeds, store the address of the string in + *RESULT and return the number of resulting bytes, excluding the trailing + NUL. Upon memory allocation error, or some other error, return -1. */ + extern int asprintf (char **result, const char *format, ...) + __attribute__ ((__format__ (__printf__, 2, 3))); + extern int vasprintf (char **result, const char *format, va_list args) + __attribute__ ((__format__ (__printf__, 2, 0))); +# endif +#endif + +#if 0 +# if 0 +# define fopen rpl_fopen +extern FILE * fopen (const char *filename, const char *mode); +# endif +#elif defined GNULIB_POSIXCHECK +# undef fopen +# define fopen(f,m) \ + (GL_LINK_WARNING ("fopen on Win32 platforms is not POSIX compatible - " \ + "use gnulib module fopen for portability"), \ + fopen (f, m)) +#endif + +#if 0 +# if 0 +# define freopen rpl_freopen +extern FILE * freopen (const char *filename, const char *mode, FILE *stream); +# endif +#elif defined GNULIB_POSIXCHECK +# undef freopen +# define freopen(f,m,s) \ + (GL_LINK_WARNING ("freopen on Win32 platforms is not POSIX compatible - " \ + "use gnulib module freopen for portability"), \ + freopen (f, m, s)) +#endif + +#if 1 +# if 0 +/* Provide fseek, fseeko functions that are aware of a preceding + fflush(), and which detect pipes. */ +# define fseeko rpl_fseeko +extern int fseeko (FILE *fp, off_t offset, int whence); +# define fseek(fp, offset, whence) fseeko (fp, (off_t)(offset), whence) +# endif +#elif defined GNULIB_POSIXCHECK +# undef fseeko +# define fseeko(f,o,w) \ + (GL_LINK_WARNING ("fseeko is unportable - " \ + "use gnulib module fseeko for portability"), \ + fseeko (f, o, w)) +#endif + +#if 0 && 0 +extern int rpl_fseek (FILE *fp, long offset, int whence); +# undef fseek +# if defined GNULIB_POSIXCHECK +# define fseek(f,o,w) \ + (GL_LINK_WARNING ("fseek cannot handle files larger than 4 GB " \ + "on 32-bit platforms - " \ + "use fseeko function for handling of large files"), \ + rpl_fseek (f, o, w)) +# else +# define fseek rpl_fseek +# endif +#elif defined GNULIB_POSIXCHECK +# ifndef fseek +# define fseek(f,o,w) \ + (GL_LINK_WARNING ("fseek cannot handle files larger than 4 GB " \ + "on 32-bit platforms - " \ + "use fseeko function for handling of large files"), \ + fseek (f, o, w)) +# endif +#endif + +#if 1 +# if 0 +# define ftello rpl_ftello +extern off_t ftello (FILE *fp); +# define ftell(fp) ftello (fp) +# endif +#elif defined GNULIB_POSIXCHECK +# undef ftello +# define ftello(f) \ + (GL_LINK_WARNING ("ftello is unportable - " \ + "use gnulib module ftello for portability"), \ + ftello (f)) +#endif + +#if 0 && 0 +extern long rpl_ftell (FILE *fp); +# undef ftell +# if GNULIB_POSIXCHECK +# define ftell(f) \ + (GL_LINK_WARNING ("ftell cannot handle files larger than 4 GB " \ + "on 32-bit platforms - " \ + "use ftello function for handling of large files"), \ + rpl_ftell (f)) +# else +# define ftell rpl_ftell +# endif +#elif defined GNULIB_POSIXCHECK +# ifndef ftell +# define ftell(f) \ + (GL_LINK_WARNING ("ftell cannot handle files larger than 4 GB " \ + "on 32-bit platforms - " \ + "use ftello function for handling of large files"), \ + ftell (f)) +# endif +#endif + +#if 1 +# if 0 +# define fflush rpl_fflush + /* Flush all pending data on STREAM according to POSIX rules. Both + output and seekable input streams are supported. + Note! LOSS OF DATA can occur if fflush is applied on an input stream + that is _not_seekable_ or on an update stream that is _not_seekable_ + and in which the most recent operation was input. Seekability can + be tested with lseek(fileno(fp),0,SEEK_CUR). */ + extern int fflush (FILE *gl_stream); +# endif +#elif defined GNULIB_POSIXCHECK +# undef fflush +# define fflush(f) \ + (GL_LINK_WARNING ("fflush is not always POSIX compliant - " \ + "use gnulib module fflush for portable " \ + "POSIX compliance"), \ + fflush (f)) +#endif + +#if 1 +# if !0 +/* Read input, up to (and including) the next occurrence of DELIMITER, from + STREAM, store it in *LINEPTR (and NUL-terminate it). + *LINEPTR is a pointer returned from malloc (or NULL), pointing to *LINESIZE + bytes of space. It is realloc'd as necessary. + Return the number of bytes read and stored at *LINEPTR (not including the + NUL terminator), or -1 on error or EOF. */ +extern ssize_t getdelim (char **lineptr, size_t *linesize, int delimiter, + FILE *stream); +# endif +#elif defined GNULIB_POSIXCHECK +# undef getdelim +# define getdelim(l, s, d, f) \ + (GL_LINK_WARNING ("getdelim is unportable - " \ + "use gnulib module getdelim for portability"), \ + getdelim (l, s, d, f)) +#endif + +#if 1 +# if 0 +# undef getline +# define getline rpl_getline +# endif +# if !0 || 0 +/* Read a line, up to (and including) the next newline, from STREAM, store it + in *LINEPTR (and NUL-terminate it). + *LINEPTR is a pointer returned from malloc (or NULL), pointing to *LINESIZE + bytes of space. It is realloc'd as necessary. + Return the number of bytes read and stored at *LINEPTR (not including the + NUL terminator), or -1 on error or EOF. */ +extern ssize_t getline (char **lineptr, size_t *linesize, FILE *stream); +# endif +#elif defined GNULIB_POSIXCHECK +# undef getline +# define getline(l, s, f) \ + (GL_LINK_WARNING ("getline is unportable - " \ + "use gnulib module getline for portability"), \ + getline (l, s, f)) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _GL_STDIO_H */ +#endif /* _GL_STDIO_H */ +#endif diff --git a/src/bin/findutils/gnulib/lib/stdio.in.h b/src/bin/findutils/gnulib/lib/stdio.in.h new file mode 100644 index 0000000000..8b88626acb --- /dev/null +++ b/src/bin/findutils/gnulib/lib/stdio.in.h @@ -0,0 +1,382 @@ +/* A GNU-like . + + Copyright (C) 2004, 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#if defined __need_FILE || defined __need___FILE +/* Special invocation convention inside glibc header files. */ + +#@INCLUDE_NEXT@ @NEXT_STDIO_H@ + +#else +/* Normal invocation convention. */ + +#ifndef _GL_STDIO_H + +/* The include_next requires a split double-inclusion guard. */ +#@INCLUDE_NEXT@ @NEXT_STDIO_H@ + +#ifndef _GL_STDIO_H +#define _GL_STDIO_H + +#include +#include + +#if (@GNULIB_FSEEKO@ && @REPLACE_FSEEKO@) \ + || (@GNULIB_FTELLO@ && @REPLACE_FTELLO@) \ + || (@GNULIB_GETDELIM@ && !@HAVE_DECL_GETDELIM@) \ + || (@GNULIB_GETLINE@ && (!@HAVE_DECL_GETLINE@ || @REPLACE_GETLINE@)) +/* Get off_t and ssize_t. */ +# include +#endif + +#ifndef __attribute__ +/* This feature is available in gcc versions 2.5 and later. */ +# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__ +# define __attribute__(Spec) /* empty */ +# endif +/* The __-protected variants of `format' and `printf' attributes + are accepted by gcc versions 2.6.4 (effectively 2.7) and later. */ +# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7) +# define __format__ format +# define __printf__ printf +# endif +#endif + + +/* The definition of GL_LINK_WARNING is copied here. */ + + +#ifdef __cplusplus +extern "C" { +#endif + + +#if @GNULIB_FPRINTF_POSIX@ +# if @REPLACE_FPRINTF@ +# define fprintf rpl_fprintf +extern int fprintf (FILE *fp, const char *format, ...) + __attribute__ ((__format__ (__printf__, 2, 3))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef fprintf +# define fprintf \ + (GL_LINK_WARNING ("fprintf is not always POSIX compliant - " \ + "use gnulib module fprintf-posix for portable " \ + "POSIX compliance"), \ + fprintf) +#endif + +#if @GNULIB_VFPRINTF_POSIX@ +# if @REPLACE_VFPRINTF@ +# define vfprintf rpl_vfprintf +extern int vfprintf (FILE *fp, const char *format, va_list args) + __attribute__ ((__format__ (__printf__, 2, 0))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef vfprintf +# define vfprintf(s,f,a) \ + (GL_LINK_WARNING ("vfprintf is not always POSIX compliant - " \ + "use gnulib module vfprintf-posix for portable " \ + "POSIX compliance"), \ + vfprintf (s, f, a)) +#endif + +#if @GNULIB_PRINTF_POSIX@ +# if @REPLACE_PRINTF@ +/* Don't break __attribute__((format(printf,M,N))). */ +# define printf __printf__ +extern int printf (const char *format, ...) + __attribute__ ((__format__ (__printf__, 1, 2))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef printf +# define printf \ + (GL_LINK_WARNING ("printf is not always POSIX compliant - " \ + "use gnulib module printf-posix for portable " \ + "POSIX compliance"), \ + printf) +/* Don't break __attribute__((format(printf,M,N))). */ +# define format(kind,m,n) format (__##kind##__, m, n) +# define __format__(kind,m,n) __format__ (__##kind##__, m, n) +# define ____printf____ __printf__ +# define ____scanf____ __scanf__ +# define ____strftime____ __strftime__ +# define ____strfmon____ __strfmon__ +#endif + +#if @GNULIB_VPRINTF_POSIX@ +# if @REPLACE_VPRINTF@ +# define vprintf rpl_vprintf +extern int vprintf (const char *format, va_list args) + __attribute__ ((__format__ (__printf__, 1, 0))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef vprintf +# define vprintf(f,a) \ + (GL_LINK_WARNING ("vprintf is not always POSIX compliant - " \ + "use gnulib module vprintf-posix for portable " \ + "POSIX compliance"), \ + vprintf (f, a)) +#endif + +#if @GNULIB_SNPRINTF@ +# if @REPLACE_SNPRINTF@ +# define snprintf rpl_snprintf +# endif +# if @REPLACE_SNPRINTF@ || !@HAVE_DECL_SNPRINTF@ +extern int snprintf (char *str, size_t size, const char *format, ...) + __attribute__ ((__format__ (__printf__, 3, 4))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef snprintf +# define snprintf \ + (GL_LINK_WARNING ("snprintf is unportable - " \ + "use gnulib module snprintf for portability"), \ + snprintf) +#endif + +#if @GNULIB_VSNPRINTF@ +# if @REPLACE_VSNPRINTF@ +# define vsnprintf rpl_vsnprintf +# endif +# if @REPLACE_VSNPRINTF@ || !@HAVE_DECL_VSNPRINTF@ +extern int vsnprintf (char *str, size_t size, const char *format, va_list args) + __attribute__ ((__format__ (__printf__, 3, 0))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef vsnprintf +# define vsnprintf(b,s,f,a) \ + (GL_LINK_WARNING ("vsnprintf is unportable - " \ + "use gnulib module vsnprintf for portability"), \ + vsnprintf (b, s, f, a)) +#endif + +#if @GNULIB_SPRINTF_POSIX@ +# if @REPLACE_SPRINTF@ +# define sprintf rpl_sprintf +extern int sprintf (char *str, const char *format, ...) + __attribute__ ((__format__ (__printf__, 2, 3))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef sprintf +# define sprintf \ + (GL_LINK_WARNING ("sprintf is not always POSIX compliant - " \ + "use gnulib module sprintf-posix for portable " \ + "POSIX compliance"), \ + sprintf) +#endif + +#if @GNULIB_VSPRINTF_POSIX@ +# if @REPLACE_VSPRINTF@ +# define vsprintf rpl_vsprintf +extern int vsprintf (char *str, const char *format, va_list args) + __attribute__ ((__format__ (__printf__, 2, 0))); +# endif +#elif defined GNULIB_POSIXCHECK +# undef vsprintf +# define vsprintf(b,f,a) \ + (GL_LINK_WARNING ("vsprintf is not always POSIX compliant - " \ + "use gnulib module vsprintf-posix for portable " \ + "POSIX compliance"), \ + vsprintf (b, f, a)) +#endif + +#if @GNULIB_VASPRINTF@ +# if @REPLACE_VASPRINTF@ +# define asprintf rpl_asprintf +# define vasprintf rpl_vasprintf +# endif +# if @REPLACE_VASPRINTF@ || !@HAVE_VASPRINTF@ + /* Write formatted output to a string dynamically allocated with malloc(). + If the memory allocation succeeds, store the address of the string in + *RESULT and return the number of resulting bytes, excluding the trailing + NUL. Upon memory allocation error, or some other error, return -1. */ + extern int asprintf (char **result, const char *format, ...) + __attribute__ ((__format__ (__printf__, 2, 3))); + extern int vasprintf (char **result, const char *format, va_list args) + __attribute__ ((__format__ (__printf__, 2, 0))); +# endif +#endif + +#if @GNULIB_FOPEN@ +# if @REPLACE_FOPEN@ +# define fopen rpl_fopen +extern FILE * fopen (const char *filename, const char *mode); +# endif +#elif defined GNULIB_POSIXCHECK +# undef fopen +# define fopen(f,m) \ + (GL_LINK_WARNING ("fopen on Win32 platforms is not POSIX compatible - " \ + "use gnulib module fopen for portability"), \ + fopen (f, m)) +#endif + +#if @GNULIB_FREOPEN@ +# if @REPLACE_FREOPEN@ +# define freopen rpl_freopen +extern FILE * freopen (const char *filename, const char *mode, FILE *stream); +# endif +#elif defined GNULIB_POSIXCHECK +# undef freopen +# define freopen(f,m,s) \ + (GL_LINK_WARNING ("freopen on Win32 platforms is not POSIX compatible - " \ + "use gnulib module freopen for portability"), \ + freopen (f, m, s)) +#endif + +#if @GNULIB_FSEEKO@ +# if @REPLACE_FSEEKO@ +/* Provide fseek, fseeko functions that are aware of a preceding + fflush(), and which detect pipes. */ +# define fseeko rpl_fseeko +extern int fseeko (FILE *fp, off_t offset, int whence); +# define fseek(fp, offset, whence) fseeko (fp, (off_t)(offset), whence) +# endif +#elif defined GNULIB_POSIXCHECK +# undef fseeko +# define fseeko(f,o,w) \ + (GL_LINK_WARNING ("fseeko is unportable - " \ + "use gnulib module fseeko for portability"), \ + fseeko (f, o, w)) +#endif + +#if @GNULIB_FSEEK@ && @REPLACE_FSEEK@ +extern int rpl_fseek (FILE *fp, long offset, int whence); +# undef fseek +# if defined GNULIB_POSIXCHECK +# define fseek(f,o,w) \ + (GL_LINK_WARNING ("fseek cannot handle files larger than 4 GB " \ + "on 32-bit platforms - " \ + "use fseeko function for handling of large files"), \ + rpl_fseek (f, o, w)) +# else +# define fseek rpl_fseek +# endif +#elif defined GNULIB_POSIXCHECK +# ifndef fseek +# define fseek(f,o,w) \ + (GL_LINK_WARNING ("fseek cannot handle files larger than 4 GB " \ + "on 32-bit platforms - " \ + "use fseeko function for handling of large files"), \ + fseek (f, o, w)) +# endif +#endif + +#if @GNULIB_FTELLO@ +# if @REPLACE_FTELLO@ +# define ftello rpl_ftello +extern off_t ftello (FILE *fp); +# define ftell(fp) ftello (fp) +# endif +#elif defined GNULIB_POSIXCHECK +# undef ftello +# define ftello(f) \ + (GL_LINK_WARNING ("ftello is unportable - " \ + "use gnulib module ftello for portability"), \ + ftello (f)) +#endif + +#if @GNULIB_FTELL@ && @REPLACE_FTELL@ +extern long rpl_ftell (FILE *fp); +# undef ftell +# if GNULIB_POSIXCHECK +# define ftell(f) \ + (GL_LINK_WARNING ("ftell cannot handle files larger than 4 GB " \ + "on 32-bit platforms - " \ + "use ftello function for handling of large files"), \ + rpl_ftell (f)) +# else +# define ftell rpl_ftell +# endif +#elif defined GNULIB_POSIXCHECK +# ifndef ftell +# define ftell(f) \ + (GL_LINK_WARNING ("ftell cannot handle files larger than 4 GB " \ + "on 32-bit platforms - " \ + "use ftello function for handling of large files"), \ + ftell (f)) +# endif +#endif + +#if @GNULIB_FFLUSH@ +# if @REPLACE_FFLUSH@ +# define fflush rpl_fflush + /* Flush all pending data on STREAM according to POSIX rules. Both + output and seekable input streams are supported. + Note! LOSS OF DATA can occur if fflush is applied on an input stream + that is _not_seekable_ or on an update stream that is _not_seekable_ + and in which the most recent operation was input. Seekability can + be tested with lseek(fileno(fp),0,SEEK_CUR). */ + extern int fflush (FILE *gl_stream); +# endif +#elif defined GNULIB_POSIXCHECK +# undef fflush +# define fflush(f) \ + (GL_LINK_WARNING ("fflush is not always POSIX compliant - " \ + "use gnulib module fflush for portable " \ + "POSIX compliance"), \ + fflush (f)) +#endif + +#if @GNULIB_GETDELIM@ +# if !@HAVE_DECL_GETDELIM@ +/* Read input, up to (and including) the next occurrence of DELIMITER, from + STREAM, store it in *LINEPTR (and NUL-terminate it). + *LINEPTR is a pointer returned from malloc (or NULL), pointing to *LINESIZE + bytes of space. It is realloc'd as necessary. + Return the number of bytes read and stored at *LINEPTR (not including the + NUL terminator), or -1 on error or EOF. */ +extern ssize_t getdelim (char **lineptr, size_t *linesize, int delimiter, + FILE *stream); +# endif +#elif defined GNULIB_POSIXCHECK +# undef getdelim +# define getdelim(l, s, d, f) \ + (GL_LINK_WARNING ("getdelim is unportable - " \ + "use gnulib module getdelim for portability"), \ + getdelim (l, s, d, f)) +#endif + +#if @GNULIB_GETLINE@ +# if @REPLACE_GETLINE@ +# undef getline +# define getline rpl_getline +# endif +# if !@HAVE_DECL_GETLINE@ || @REPLACE_GETLINE@ +/* Read a line, up to (and including) the next newline, from STREAM, store it + in *LINEPTR (and NUL-terminate it). + *LINEPTR is a pointer returned from malloc (or NULL), pointing to *LINESIZE + bytes of space. It is realloc'd as necessary. + Return the number of bytes read and stored at *LINEPTR (not including the + NUL terminator), or -1 on error or EOF. */ +extern ssize_t getline (char **lineptr, size_t *linesize, FILE *stream); +# endif +#elif defined GNULIB_POSIXCHECK +# undef getline +# define getline(l, s, f) \ + (GL_LINK_WARNING ("getline is unportable - " \ + "use gnulib module getline for portability"), \ + getline (l, s, f)) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _GL_STDIO_H */ +#endif /* _GL_STDIO_H */ +#endif diff --git a/src/bin/findutils/gnulib/lib/stdlib.h b/src/bin/findutils/gnulib/lib/stdlib.h new file mode 100644 index 0000000000..341f7ddf07 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/stdlib.h @@ -0,0 +1,214 @@ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +/* A GNU-like . + + Copyright (C) 1995, 2001-2002, 2006-2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#if defined __need_malloc_and_calloc +/* Special invocation convention inside glibc header files. */ + +#include_next + +#else +/* Normal invocation convention. */ + +#ifndef _GL_STDLIB_H + +/* The include_next requires a split double-inclusion guard. */ +#include_next + +#ifndef _GL_STDLIB_H +#define _GL_STDLIB_H + + +/* The definition of GL_LINK_WARNING is copied here. */ +/* GL_LINK_WARNING("literal string") arranges to emit the literal string as + a linker warning on most glibc systems. + We use a linker warning rather than a preprocessor warning, because + #warning cannot be used inside macros. */ +#ifndef GL_LINK_WARNING + /* This works on platforms with GNU ld and ELF object format. + Testing __GLIBC__ is sufficient for asserting that GNU ld is in use. + Testing __ELF__ guarantees the ELF object format. + Testing __GNUC__ is necessary for the compound expression syntax. */ +# if defined __GLIBC__ && defined __ELF__ && defined __GNUC__ +# define GL_LINK_WARNING(message) \ + GL_LINK_WARNING1 (__FILE__, __LINE__, message) +# define GL_LINK_WARNING1(file, line, message) \ + GL_LINK_WARNING2 (file, line, message) /* macroexpand file and line */ +# define GL_LINK_WARNING2(file, line, message) \ + GL_LINK_WARNING3 (file ":" #line ": warning: " message) +# define GL_LINK_WARNING3(message) \ + ({ static const char warning[sizeof (message)] \ + __attribute__ ((__unused__, \ + __section__ (".gnu.warning"), \ + __aligned__ (1))) \ + = message "\n"; \ + (void)0; \ + }) +# else +# define GL_LINK_WARNING(message) ((void) 0) +# endif +#endif + + +/* Some systems do not define EXIT_*, despite otherwise supporting C89. */ +#ifndef EXIT_SUCCESS +# define EXIT_SUCCESS 0 +#endif +/* Tandem/NSK and other platforms that define EXIT_FAILURE as -1 interfere + with proper operation of xargs. */ +#ifndef EXIT_FAILURE +# define EXIT_FAILURE 1 +#elif EXIT_FAILURE != 1 +# undef EXIT_FAILURE +# define EXIT_FAILURE 1 +#endif + + +#ifdef __cplusplus +extern "C" { +#endif + + +#if 1 +# if !1 +# undef malloc +# define malloc rpl_malloc +extern void * malloc (size_t size); +# endif +#elif defined GNULIB_POSIXCHECK +# undef malloc +# define malloc(s) \ + (GL_LINK_WARNING ("malloc is not POSIX compliant everywhere - " \ + "use gnulib module malloc-posix for portability"), \ + malloc (s)) +#endif + + +#if 1 +# if !1 +# undef realloc +# define realloc rpl_realloc +extern void * realloc (void *ptr, size_t size); +# endif +#elif defined GNULIB_POSIXCHECK +# undef realloc +# define realloc(p,s) \ + (GL_LINK_WARNING ("realloc is not POSIX compliant everywhere - " \ + "use gnulib module realloc-posix for portability"), \ + realloc (p, s)) +#endif + + +#if 0 +# if !1 +# undef calloc +# define calloc rpl_calloc +extern void * calloc (size_t nmemb, size_t size); +# endif +#elif defined GNULIB_POSIXCHECK +# undef calloc +# define calloc(n,s) \ + (GL_LINK_WARNING ("calloc is not POSIX compliant everywhere - " \ + "use gnulib module calloc-posix for portability"), \ + calloc (n, s)) +#endif + + +#if 0 +/* Assuming *OPTIONP is a comma separated list of elements of the form + "token" or "token=value", getsubopt parses the first of these elements. + If the first element refers to a "token" that is member of the given + NULL-terminated array of tokens: + - It replaces the comma with a NUL byte, updates *OPTIONP to point past + the first option and the comma, sets *VALUEP to the value of the + element (or NULL if it doesn't contain an "=" sign), + - It returns the index of the "token" in the given array of tokens. + Otherwise it returns -1, and *OPTIONP and *VALUEP are undefined. + For more details see the POSIX:2001 specification. + http://www.opengroup.org/susv3xsh/getsubopt.html */ +# if !1 +extern int getsubopt (char **optionp, char *const *tokens, char **valuep); +# endif +#elif defined GNULIB_POSIXCHECK +# undef getsubopt +# define getsubopt(o,t,v) \ + (GL_LINK_WARNING ("getsubopt is unportable - " \ + "use gnulib module getsubopt for portability"), \ + getsubopt (o, t, v)) +#endif + + +#if 0 +# if !1 +/* Create a unique temporary directory from TEMPLATE. + The last six characters of TEMPLATE must be "XXXXXX"; + they are replaced with a string that makes the directory name unique. + Returns TEMPLATE, or a null pointer if it cannot get a unique name. + The directory is created mode 700. */ +extern char * mkdtemp (char * /*template*/); +# endif +#elif defined GNULIB_POSIXCHECK +# undef mkdtemp +# define mkdtemp(t) \ + (GL_LINK_WARNING ("mkdtemp is unportable - " \ + "use gnulib module mkdtemp for portability"), \ + mkdtemp (t)) +#endif + + +#if 0 +# if 0 +/* Create a unique temporary file from TEMPLATE. + The last six characters of TEMPLATE must be "XXXXXX"; + they are replaced with a string that makes the file name unique. + The file is then created, ensuring it didn't exist before. + The file is created read-write (mask at least 0600 & ~umask), but it may be + world-readable and world-writable (mask 0666 & ~umask), depending on the + implementation. + Returns the open file descriptor if successful, otherwise -1 and errno + set. */ +# define mkstemp rpl_mkstemp +extern int mkstemp (char * /*template*/); +# else +/* On MacOS X 10.3, only declares mkstemp. */ +# include +# endif +#elif defined GNULIB_POSIXCHECK +# undef mkstemp +# define mkstemp(t) \ + (GL_LINK_WARNING ("mkstemp is unportable - " \ + "use gnulib module mkstemp for portability"), \ + mkstemp (t)) +#endif + + +#if 0 +# if 0 +# undef putenv +# define putenv rpl_putenv +extern int putenv (char *string); +# endif +#endif + + +#ifdef __cplusplus +} +#endif + +#endif /* _GL_STDLIB_H */ +#endif /* _GL_STDLIB_H */ +#endif diff --git a/src/bin/findutils/gnulib/lib/stdlib.in.h b/src/bin/findutils/gnulib/lib/stdlib.in.h new file mode 100644 index 0000000000..dc9f98f8d3 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/stdlib.in.h @@ -0,0 +1,185 @@ +/* A GNU-like . + + Copyright (C) 1995, 2001-2002, 2006-2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#if defined __need_malloc_and_calloc +/* Special invocation convention inside glibc header files. */ + +#@INCLUDE_NEXT@ @NEXT_STDLIB_H@ + +#else +/* Normal invocation convention. */ + +#ifndef _GL_STDLIB_H + +/* The include_next requires a split double-inclusion guard. */ +#@INCLUDE_NEXT@ @NEXT_STDLIB_H@ + +#ifndef _GL_STDLIB_H +#define _GL_STDLIB_H + + +/* The definition of GL_LINK_WARNING is copied here. */ + + +/* Some systems do not define EXIT_*, despite otherwise supporting C89. */ +#ifndef EXIT_SUCCESS +# define EXIT_SUCCESS 0 +#endif +/* Tandem/NSK and other platforms that define EXIT_FAILURE as -1 interfere + with proper operation of xargs. */ +#ifndef EXIT_FAILURE +# define EXIT_FAILURE 1 +#elif EXIT_FAILURE != 1 +# undef EXIT_FAILURE +# define EXIT_FAILURE 1 +#endif + + +#ifdef __cplusplus +extern "C" { +#endif + + +#if @GNULIB_MALLOC_POSIX@ +# if !@HAVE_MALLOC_POSIX@ +# undef malloc +# define malloc rpl_malloc +extern void * malloc (size_t size); +# endif +#elif defined GNULIB_POSIXCHECK +# undef malloc +# define malloc(s) \ + (GL_LINK_WARNING ("malloc is not POSIX compliant everywhere - " \ + "use gnulib module malloc-posix for portability"), \ + malloc (s)) +#endif + + +#if @GNULIB_REALLOC_POSIX@ +# if !@HAVE_REALLOC_POSIX@ +# undef realloc +# define realloc rpl_realloc +extern void * realloc (void *ptr, size_t size); +# endif +#elif defined GNULIB_POSIXCHECK +# undef realloc +# define realloc(p,s) \ + (GL_LINK_WARNING ("realloc is not POSIX compliant everywhere - " \ + "use gnulib module realloc-posix for portability"), \ + realloc (p, s)) +#endif + + +#if @GNULIB_CALLOC_POSIX@ +# if !@HAVE_CALLOC_POSIX@ +# undef calloc +# define calloc rpl_calloc +extern void * calloc (size_t nmemb, size_t size); +# endif +#elif defined GNULIB_POSIXCHECK +# undef calloc +# define calloc(n,s) \ + (GL_LINK_WARNING ("calloc is not POSIX compliant everywhere - " \ + "use gnulib module calloc-posix for portability"), \ + calloc (n, s)) +#endif + + +#if @GNULIB_GETSUBOPT@ +/* Assuming *OPTIONP is a comma separated list of elements of the form + "token" or "token=value", getsubopt parses the first of these elements. + If the first element refers to a "token" that is member of the given + NULL-terminated array of tokens: + - It replaces the comma with a NUL byte, updates *OPTIONP to point past + the first option and the comma, sets *VALUEP to the value of the + element (or NULL if it doesn't contain an "=" sign), + - It returns the index of the "token" in the given array of tokens. + Otherwise it returns -1, and *OPTIONP and *VALUEP are undefined. + For more details see the POSIX:2001 specification. + http://www.opengroup.org/susv3xsh/getsubopt.html */ +# if !@HAVE_GETSUBOPT@ +extern int getsubopt (char **optionp, char *const *tokens, char **valuep); +# endif +#elif defined GNULIB_POSIXCHECK +# undef getsubopt +# define getsubopt(o,t,v) \ + (GL_LINK_WARNING ("getsubopt is unportable - " \ + "use gnulib module getsubopt for portability"), \ + getsubopt (o, t, v)) +#endif + + +#if @GNULIB_MKDTEMP@ +# if !@HAVE_MKDTEMP@ +/* Create a unique temporary directory from TEMPLATE. + The last six characters of TEMPLATE must be "XXXXXX"; + they are replaced with a string that makes the directory name unique. + Returns TEMPLATE, or a null pointer if it cannot get a unique name. + The directory is created mode 700. */ +extern char * mkdtemp (char * /*template*/); +# endif +#elif defined GNULIB_POSIXCHECK +# undef mkdtemp +# define mkdtemp(t) \ + (GL_LINK_WARNING ("mkdtemp is unportable - " \ + "use gnulib module mkdtemp for portability"), \ + mkdtemp (t)) +#endif + + +#if @GNULIB_MKSTEMP@ +# if @REPLACE_MKSTEMP@ +/* Create a unique temporary file from TEMPLATE. + The last six characters of TEMPLATE must be "XXXXXX"; + they are replaced with a string that makes the file name unique. + The file is then created, ensuring it didn't exist before. + The file is created read-write (mask at least 0600 & ~umask), but it may be + world-readable and world-writable (mask 0666 & ~umask), depending on the + implementation. + Returns the open file descriptor if successful, otherwise -1 and errno + set. */ +# define mkstemp rpl_mkstemp +extern int mkstemp (char * /*template*/); +# else +/* On MacOS X 10.3, only declares mkstemp. */ +# include +# endif +#elif defined GNULIB_POSIXCHECK +# undef mkstemp +# define mkstemp(t) \ + (GL_LINK_WARNING ("mkstemp is unportable - " \ + "use gnulib module mkstemp for portability"), \ + mkstemp (t)) +#endif + + +#if @GNULIB_PUTENV@ +# if @REPLACE_PUTENV@ +# undef putenv +# define putenv rpl_putenv +extern int putenv (char *string); +# endif +#endif + + +#ifdef __cplusplus +} +#endif + +#endif /* _GL_STDLIB_H */ +#endif /* _GL_STDLIB_H */ +#endif diff --git a/src/bin/findutils/gnulib/lib/stpcpy.c b/src/bin/findutils/gnulib/lib/stpcpy.c new file mode 100644 index 0000000000..1e70013382 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/stpcpy.c @@ -0,0 +1,48 @@ +/* stpcpy.c -- copy a string and return pointer to end of new string + Copyright (C) 1992, 1995, 1997-1998, 2006 Free Software Foundation, Inc. + + NOTE: The canonical source of this file is maintained with the GNU C Library. + Bugs can be reported to bug-glibc@prep.ai.mit.edu. + + This program is free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation; either version 3 of the License, or any + later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include + +#undef __stpcpy +#ifdef _LIBC +# undef stpcpy +#endif + +#ifndef weak_alias +# define __stpcpy stpcpy +#endif + +/* Copy SRC to DEST, returning the address of the terminating '\0' in DEST. */ +char * +__stpcpy (char *dest, const char *src) +{ + register char *d = dest; + register const char *s = src; + + do + *d++ = *s; + while (*s++ != '\0'); + + return d - 1; +} +#ifdef weak_alias +weak_alias (__stpcpy, stpcpy) +#endif diff --git a/src/bin/findutils/gnulib/lib/strdup.c b/src/bin/findutils/gnulib/lib/strdup.c new file mode 100644 index 0000000000..bebe5c8fb4 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/strdup.c @@ -0,0 +1,55 @@ +/* Copyright (C) 1991, 1996, 1997, 1998, 2002, 2003, 2004, 2006, 2007 Free + Software Foundation, Inc. + + This file is part of the GNU C Library. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _LIBC +# include +#endif + +/* Get specification. */ +#include + +#include + +#undef __strdup +#ifdef _LIBC +# undef strdup +#endif + +#ifndef weak_alias +# define __strdup strdup +#endif + +/* Duplicate S, returning an identical malloc'd string. */ +char * +__strdup (const char *s) +{ + size_t len = strlen (s) + 1; + void *new = malloc (len); + + if (new == NULL) + return NULL; + + return (char *) memcpy (new, s, len); +} +#ifdef libc_hidden_def +libc_hidden_def (__strdup) +#endif +#ifdef weak_alias +weak_alias (__strdup, strdup) +#endif diff --git a/src/bin/findutils/gnulib/lib/strerror.c b/src/bin/findutils/gnulib/lib/strerror.c new file mode 100644 index 0000000000..9fe437db78 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/strerror.c @@ -0,0 +1,49 @@ +/* strerror.c --- POSIX compatible system error routine + + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include + +#if REPLACE_STRERROR + +# include + +# include "intprops.h" + +# undef strerror +# if ! HAVE_DECL_STRERROR +# define strerror(n) NULL +# endif + +char * +rpl_strerror (int n) +{ + char *result = strerror (n); + + if (result == NULL || result[0] == '\0') + { + static char const fmt[] = "Unknown error (%d)"; + static char mesg[sizeof fmt + INT_STRLEN_BOUND (n)]; + sprintf (mesg, fmt, n); + return mesg; + } + + return result; +} + +#endif diff --git a/src/bin/findutils/gnulib/lib/strftime.c b/src/bin/findutils/gnulib/lib/strftime.c new file mode 100644 index 0000000000..c6a9c8040d --- /dev/null +++ b/src/bin/findutils/gnulib/lib/strftime.c @@ -0,0 +1,1461 @@ +/* Copyright (C) 1991-1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007 Free Software + Foundation, Inc. + + NOTE: The canonical source of this file is maintained with the GNU C Library. + Bugs can be reported to bug-glibc@prep.ai.mit.edu. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifdef _LIBC +# define HAVE_MBLEN 1 +# define HAVE_MBRLEN 1 +# define HAVE_STRUCT_ERA_ENTRY 1 +# define HAVE_TM_GMTOFF 1 +# define HAVE_TM_ZONE 1 +# define HAVE_TZNAME 1 +# define HAVE_TZSET 1 +# define MULTIBYTE_IS_FORMAT_SAFE 1 +# include "../locale/localeinfo.h" +#else +# include +# if FPRINTFTIME +# include "fprintftime.h" +# endif +#endif + +#include +#include + +#if HAVE_TZNAME && ! defined tzname +extern char *tzname[]; +#endif + +/* Do multibyte processing if multibytes are supported, unless + multibyte sequences are safe in formats. Multibyte sequences are + safe if they cannot contain byte sequences that look like format + conversion specifications. The GNU C Library uses UTF8 multibyte + encoding, which is safe for formats, but strftime.c can be used + with other C libraries that use unsafe encodings. */ +#define DO_MULTIBYTE (HAVE_MBLEN && ! MULTIBYTE_IS_FORMAT_SAFE) + +#if DO_MULTIBYTE +# if HAVE_MBRLEN +# include +# else + /* Simulate mbrlen with mblen as best we can. */ +# define mbstate_t int +# define mbrlen(s, n, ps) mblen (s, n) +# define mbsinit(ps) (*(ps) == 0) +# endif + static const mbstate_t mbstate_zero; +#endif + +#include +#include +#include +#include +#include + +#ifdef COMPILE_WIDE +# include +# define CHAR_T wchar_t +# define UCHAR_T unsigned int +# define L_(Str) L##Str +# define NLW(Sym) _NL_W##Sym + +# define MEMCPY(d, s, n) __wmemcpy (d, s, n) +# define STRLEN(s) __wcslen (s) + +#else +# define CHAR_T char +# define UCHAR_T unsigned char +# define L_(Str) Str +# define NLW(Sym) Sym + +# define MEMCPY(d, s, n) memcpy (d, s, n) +# define STRLEN(s) strlen (s) + +# ifdef _LIBC +# define MEMPCPY(d, s, n) __mempcpy (d, s, n) +# else +# ifndef HAVE_MEMPCPY +# define MEMPCPY(d, s, n) ((void *) ((char *) memcpy (d, s, n) + (n))) +# endif +# endif +#endif + +/* Shift A right by B bits portably, by dividing A by 2**B and + truncating towards minus infinity. A and B should be free of side + effects, and B should be in the range 0 <= B <= INT_BITS - 2, where + INT_BITS is the number of useful bits in an int. GNU code can + assume that INT_BITS is at least 32. + + ISO C99 says that A >> B is implementation-defined if A < 0. Some + implementations (e.g., UNICOS 9.0 on a Cray Y-MP EL) don't shift + right in the usual way when A < 0, so SHR falls back on division if + ordinary A >> B doesn't seem to be the usual signed shift. */ +#define SHR(a, b) \ + (-1 >> 1 == -1 \ + ? (a) >> (b) \ + : (a) / (1 << (b)) - ((a) % (1 << (b)) < 0)) + +/* Bound on length of the string representing an integer type or expression T. + Subtract 1 for the sign bit if t is signed; log10 (2.0) < 146/485; + add 1 for integer division truncation; add 1 more for a minus sign + if needed. */ +#define INT_STRLEN_BOUND(t) \ + ((sizeof (t) * CHAR_BIT - 1) * 146 / 485 + 2) + +#define TM_YEAR_BASE 1900 + +#ifndef __isleap +/* Nonzero if YEAR is a leap year (every 4 years, + except every 100th isn't, and every 400th is). */ +# define __isleap(year) \ + ((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0)) +#endif + + +#ifdef _LIBC +# define tzname __tzname +# define tzset __tzset +#endif + +#if !HAVE_TM_GMTOFF +/* Portable standalone applications should supply a "time.h" that + declares a POSIX-compliant localtime_r, for the benefit of older + implementations that lack localtime_r or have a nonstandard one. + See the gnulib time_r module for one way to implement this. */ +# undef __gmtime_r +# undef __localtime_r +# define __gmtime_r gmtime_r +# define __localtime_r localtime_r +#endif + + +#ifndef FPRINTFTIME +# define FPRINTFTIME 0 +#endif + +#if FPRINTFTIME +# define STREAM_OR_CHAR_T FILE +# define STRFTIME_ARG(x) /* empty */ +#else +# define STREAM_OR_CHAR_T CHAR_T +# define STRFTIME_ARG(x) x, +#endif + +#if FPRINTFTIME +# define memset_byte(P, Len, Byte) \ + do { size_t _i; for (_i = 0; _i < Len; _i++) fputc (Byte, P); } while (0) +# define memset_space(P, Len) memset_byte (P, Len, ' ') +# define memset_zero(P, Len) memset_byte (P, Len, '0') +#elif defined COMPILE_WIDE +# define memset_space(P, Len) (wmemset (P, L' ', Len), (P) += (Len)) +# define memset_zero(P, Len) (wmemset (P, L'0', Len), (P) += (Len)) +#else +# define memset_space(P, Len) (memset (P, ' ', Len), (P) += (Len)) +# define memset_zero(P, Len) (memset (P, '0', Len), (P) += (Len)) +#endif + +#if FPRINTFTIME +# define advance(P, N) +#else +# define advance(P, N) ((P) += (N)) +#endif + +#define add(n, f) \ + do \ + { \ + int _n = (n); \ + int _delta = width - _n; \ + int _incr = _n + (_delta > 0 ? _delta : 0); \ + if ((size_t) _incr >= maxsize - i) \ + return 0; \ + if (p) \ + { \ + if (digits == 0 && _delta > 0) \ + { \ + if (pad == L_('0')) \ + memset_zero (p, _delta); \ + else \ + memset_space (p, _delta); \ + } \ + f; \ + advance (p, _n); \ + } \ + i += _incr; \ + } while (0) + +#if FPRINTFTIME +# define add1(C) add (1, fputc (C, p)) +#else +# define add1(C) add (1, *p = C) +#endif + +#if FPRINTFTIME +# define cpy(n, s) \ + add ((n), \ + if (to_lowcase) \ + fwrite_lowcase (p, (s), _n); \ + else if (to_uppcase) \ + fwrite_uppcase (p, (s), _n); \ + else \ + fwrite ((s), _n, 1, p)) +#else +# define cpy(n, s) \ + add ((n), \ + if (to_lowcase) \ + memcpy_lowcase (p, (s), _n LOCALE_ARG); \ + else if (to_uppcase) \ + memcpy_uppcase (p, (s), _n LOCALE_ARG); \ + else \ + MEMCPY ((void *) p, (void const *) (s), _n)) +#endif + +#ifdef COMPILE_WIDE +# ifndef USE_IN_EXTENDED_LOCALE_MODEL +# undef __mbsrtowcs_l +# define __mbsrtowcs_l(d, s, l, st, loc) __mbsrtowcs (d, s, l, st) +# endif +# define widen(os, ws, l) \ + { \ + mbstate_t __st; \ + const char *__s = os; \ + memset (&__st, '\0', sizeof (__st)); \ + l = __mbsrtowcs_l (NULL, &__s, 0, &__st, loc); \ + ws = (wchar_t *) alloca ((l + 1) * sizeof (wchar_t)); \ + (void) __mbsrtowcs_l (ws, &__s, l, &__st, loc); \ + } +#endif + + +#if defined _LIBC && defined USE_IN_EXTENDED_LOCALE_MODEL +/* We use this code also for the extended locale handling where the + function gets as an additional argument the locale which has to be + used. To access the values we have to redefine the _NL_CURRENT + macro. */ +# define strftime __strftime_l +# define wcsftime __wcsftime_l +# undef _NL_CURRENT +# define _NL_CURRENT(category, item) \ + (current->values[_NL_ITEM_INDEX (item)].string) +# define LOCALE_ARG , loc +# define LOCALE_PARAM_PROTO , __locale_t loc +# define HELPER_LOCALE_ARG , current +#else +# define LOCALE_PARAM_PROTO +# define LOCALE_ARG +# ifdef _LIBC +# define HELPER_LOCALE_ARG , _NL_CURRENT_DATA (LC_TIME) +# else +# define HELPER_LOCALE_ARG +# endif +#endif + +#ifdef COMPILE_WIDE +# ifdef USE_IN_EXTENDED_LOCALE_MODEL +# define TOUPPER(Ch, L) __towupper_l (Ch, L) +# define TOLOWER(Ch, L) __towlower_l (Ch, L) +# else +# define TOUPPER(Ch, L) towupper (Ch) +# define TOLOWER(Ch, L) towlower (Ch) +# endif +#else +# ifdef USE_IN_EXTENDED_LOCALE_MODEL +# define TOUPPER(Ch, L) __toupper_l (Ch, L) +# define TOLOWER(Ch, L) __tolower_l (Ch, L) +# else +# define TOUPPER(Ch, L) toupper (Ch) +# define TOLOWER(Ch, L) tolower (Ch) +# endif +#endif +/* We don't use `isdigit' here since the locale dependent + interpretation is not what we want here. We only need to accept + the arabic digits in the ASCII range. One day there is perhaps a + more reliable way to accept other sets of digits. */ +#define ISDIGIT(Ch) ((unsigned int) (Ch) - L_('0') <= 9) + +#if FPRINTFTIME +static void +fwrite_lowcase (FILE *fp, const CHAR_T *src, size_t len) +{ + while (len-- > 0) + { + fputc (TOLOWER ((UCHAR_T) *src, loc), fp); + ++src; + } +} + +static void +fwrite_uppcase (FILE *fp, const CHAR_T *src, size_t len) +{ + while (len-- > 0) + { + fputc (TOUPPER ((UCHAR_T) *src, loc), fp); + ++src; + } +} +#else +static CHAR_T * +memcpy_lowcase (CHAR_T *dest, const CHAR_T *src, + size_t len LOCALE_PARAM_PROTO) +{ + while (len-- > 0) + dest[len] = TOLOWER ((UCHAR_T) src[len], loc); + return dest; +} + +static CHAR_T * +memcpy_uppcase (CHAR_T *dest, const CHAR_T *src, + size_t len LOCALE_PARAM_PROTO) +{ + while (len-- > 0) + dest[len] = TOUPPER ((UCHAR_T) src[len], loc); + return dest; +} +#endif + + +#if ! HAVE_TM_GMTOFF +/* Yield the difference between *A and *B, + measured in seconds, ignoring leap seconds. */ +# define tm_diff ftime_tm_diff +static int +tm_diff (const struct tm *a, const struct tm *b) +{ + /* Compute intervening leap days correctly even if year is negative. + Take care to avoid int overflow in leap day calculations, + but it's OK to assume that A and B are close to each other. */ + int a4 = SHR (a->tm_year, 2) + SHR (TM_YEAR_BASE, 2) - ! (a->tm_year & 3); + int b4 = SHR (b->tm_year, 2) + SHR (TM_YEAR_BASE, 2) - ! (b->tm_year & 3); + int a100 = a4 / 25 - (a4 % 25 < 0); + int b100 = b4 / 25 - (b4 % 25 < 0); + int a400 = SHR (a100, 2); + int b400 = SHR (b100, 2); + int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400); + int years = a->tm_year - b->tm_year; + int days = (365 * years + intervening_leap_days + + (a->tm_yday - b->tm_yday)); + return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour)) + + (a->tm_min - b->tm_min)) + + (a->tm_sec - b->tm_sec)); +} +#endif /* ! HAVE_TM_GMTOFF */ + + + +/* The number of days from the first day of the first ISO week of this + year to the year day YDAY with week day WDAY. ISO weeks start on + Monday; the first ISO week has the year's first Thursday. YDAY may + be as small as YDAY_MINIMUM. */ +#define ISO_WEEK_START_WDAY 1 /* Monday */ +#define ISO_WEEK1_WDAY 4 /* Thursday */ +#define YDAY_MINIMUM (-366) +#ifdef __GNUC__ +__inline__ +#endif +static int +iso_week_days (int yday, int wday) +{ + /* Add enough to the first operand of % to make it nonnegative. */ + int big_enough_multiple_of_7 = (-YDAY_MINIMUM / 7 + 2) * 7; + return (yday + - (yday - wday + ISO_WEEK1_WDAY + big_enough_multiple_of_7) % 7 + + ISO_WEEK1_WDAY - ISO_WEEK_START_WDAY); +} + + +/* When compiling this file, GNU applications can #define my_strftime + to a symbol (typically nstrftime) to get an extended strftime with + extra arguments UT and NS. Emacs is a special case for now, but + this Emacs-specific code can be removed once Emacs's config.h + defines my_strftime. */ +#if defined emacs && !defined my_strftime +# define my_strftime nstrftime +#endif + +#if FPRINTFTIME +# undef my_strftime +# define my_strftime fprintftime +#endif + +#ifdef my_strftime +# define extra_args , ut, ns +# define extra_args_spec , int ut, int ns +#else +# if defined COMPILE_WIDE +# define my_strftime wcsftime +# define nl_get_alt_digit _nl_get_walt_digit +# else +# define my_strftime strftime +# define nl_get_alt_digit _nl_get_alt_digit +# endif +# define extra_args +# define extra_args_spec +/* We don't have this information in general. */ +# define ut 0 +# define ns 0 +#endif + + +/* Just like my_strftime, below, but with one more parameter, UPCASE, + to indicate that the result should be converted to upper case. */ +static size_t +strftime_case_ (bool upcase, STREAM_OR_CHAR_T *s, + STRFTIME_ARG (size_t maxsize) + const CHAR_T *format, + const struct tm *tp extra_args_spec LOCALE_PARAM_PROTO) +{ +#if defined _LIBC && defined USE_IN_EXTENDED_LOCALE_MODEL + struct locale_data *const current = loc->__locales[LC_TIME]; +#endif +#if FPRINTFTIME + size_t maxsize = (size_t) -1; +#endif + + int hour12 = tp->tm_hour; +#ifdef _NL_CURRENT + /* We cannot make the following values variables since we must delay + the evaluation of these values until really needed since some + expressions might not be valid in every situation. The `struct tm' + might be generated by a strptime() call that initialized + only a few elements. Dereference the pointers only if the format + requires this. Then it is ok to fail if the pointers are invalid. */ +# define a_wkday \ + ((const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(ABDAY_1) + tp->tm_wday)) +# define f_wkday \ + ((const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(DAY_1) + tp->tm_wday)) +# define a_month \ + ((const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(ABMON_1) + tp->tm_mon)) +# define f_month \ + ((const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(MON_1) + tp->tm_mon)) +# define ampm \ + ((const CHAR_T *) _NL_CURRENT (LC_TIME, tp->tm_hour > 11 \ + ? NLW(PM_STR) : NLW(AM_STR))) + +# define aw_len STRLEN (a_wkday) +# define am_len STRLEN (a_month) +# define ap_len STRLEN (ampm) +#endif + const char *zone; + size_t i = 0; + STREAM_OR_CHAR_T *p = s; + const CHAR_T *f; +#if DO_MULTIBYTE && !defined COMPILE_WIDE + const char *format_end = NULL; +#endif + +#if ! defined _LIBC && ! HAVE_RUN_TZSET_TEST + /* Solaris 2.5.x and 2.6 tzset sometimes modify the storage returned + by localtime. On such systems, we must either use the tzset and + localtime wrappers to work around the bug (which sets + HAVE_RUN_TZSET_TEST) or make a copy of the structure. */ + struct tm copy = *tp; + tp = © +#endif + + zone = NULL; +#if HAVE_TM_ZONE + /* The POSIX test suite assumes that setting + the environment variable TZ to a new value before calling strftime() + will influence the result (the %Z format) even if the information in + TP is computed with a totally different time zone. + This is bogus: though POSIX allows bad behavior like this, + POSIX does not require it. Do the right thing instead. */ + zone = (const char *) tp->tm_zone; +#endif +#if HAVE_TZNAME + if (ut) + { + if (! (zone && *zone)) + zone = "GMT"; + } + else + { + /* POSIX.1 requires that local time zone information be used as + though strftime called tzset. */ +# if HAVE_TZSET + tzset (); +# endif + } +#endif + + if (hour12 > 12) + hour12 -= 12; + else + if (hour12 == 0) + hour12 = 12; + + for (f = format; *f != '\0'; ++f) + { + int pad = 0; /* Padding for number ('-', '_', or 0). */ + int modifier; /* Field modifier ('E', 'O', or 0). */ + int digits = 0; /* Max digits for numeric format. */ + int number_value; /* Numeric value to be printed. */ + unsigned int u_number_value; /* (unsigned int) number_value. */ + bool negative_number; /* The number is negative. */ + bool always_output_a_sign; /* +/- should always be output. */ + int tz_colon_mask; /* Bitmask of where ':' should appear. */ + const CHAR_T *subfmt; + CHAR_T sign_char; + CHAR_T *bufp; + CHAR_T buf[1 + + 2 /* for the two colons in a %::z or %:::z time zone */ + + (sizeof (int) < sizeof (time_t) + ? INT_STRLEN_BOUND (time_t) + : INT_STRLEN_BOUND (int))]; + int width = -1; + bool to_lowcase = false; + bool to_uppcase = upcase; + size_t colons; + bool change_case = false; + int format_char; + +#if DO_MULTIBYTE && !defined COMPILE_WIDE + switch (*f) + { + case L_('%'): + break; + + case L_('\b'): case L_('\t'): case L_('\n'): + case L_('\v'): case L_('\f'): case L_('\r'): + case L_(' '): case L_('!'): case L_('"'): case L_('#'): case L_('&'): + case L_('\''): case L_('('): case L_(')'): case L_('*'): case L_('+'): + case L_(','): case L_('-'): case L_('.'): case L_('/'): case L_('0'): + case L_('1'): case L_('2'): case L_('3'): case L_('4'): case L_('5'): + case L_('6'): case L_('7'): case L_('8'): case L_('9'): case L_(':'): + case L_(';'): case L_('<'): case L_('='): case L_('>'): case L_('?'): + case L_('A'): case L_('B'): case L_('C'): case L_('D'): case L_('E'): + case L_('F'): case L_('G'): case L_('H'): case L_('I'): case L_('J'): + case L_('K'): case L_('L'): case L_('M'): case L_('N'): case L_('O'): + case L_('P'): case L_('Q'): case L_('R'): case L_('S'): case L_('T'): + case L_('U'): case L_('V'): case L_('W'): case L_('X'): case L_('Y'): + case L_('Z'): case L_('['): case L_('\\'): case L_(']'): case L_('^'): + case L_('_'): case L_('a'): case L_('b'): case L_('c'): case L_('d'): + case L_('e'): case L_('f'): case L_('g'): case L_('h'): case L_('i'): + case L_('j'): case L_('k'): case L_('l'): case L_('m'): case L_('n'): + case L_('o'): case L_('p'): case L_('q'): case L_('r'): case L_('s'): + case L_('t'): case L_('u'): case L_('v'): case L_('w'): case L_('x'): + case L_('y'): case L_('z'): case L_('{'): case L_('|'): case L_('}'): + case L_('~'): + /* The C Standard requires these 98 characters (plus '%') to + be in the basic execution character set. None of these + characters can start a multibyte sequence, so they need + not be analyzed further. */ + add1 (*f); + continue; + + default: + /* Copy this multibyte sequence until we reach its end, find + an error, or come back to the initial shift state. */ + { + mbstate_t mbstate = mbstate_zero; + size_t len = 0; + size_t fsize; + + if (! format_end) + format_end = f + strlen (f) + 1; + fsize = format_end - f; + + do + { + size_t bytes = mbrlen (f + len, fsize - len, &mbstate); + + if (bytes == 0) + break; + + if (bytes == (size_t) -2) + { + len += strlen (f + len); + break; + } + + if (bytes == (size_t) -1) + { + len++; + break; + } + + len += bytes; + } + while (! mbsinit (&mbstate)); + + cpy (len, f); + f += len - 1; + continue; + } + } + +#else /* ! DO_MULTIBYTE */ + + /* Either multibyte encodings are not supported, they are + safe for formats, so any non-'%' byte can be copied through, + or this is the wide character version. */ + if (*f != L_('%')) + { + add1 (*f); + continue; + } + +#endif /* ! DO_MULTIBYTE */ + + /* Check for flags that can modify a format. */ + while (1) + { + switch (*++f) + { + /* This influences the number formats. */ + case L_('_'): + case L_('-'): + case L_('0'): + pad = *f; + continue; + + /* This changes textual output. */ + case L_('^'): + to_uppcase = true; + continue; + case L_('#'): + change_case = true; + continue; + + default: + break; + } + break; + } + + /* As a GNU extension we allow to specify the field width. */ + if (ISDIGIT (*f)) + { + width = 0; + do + { + if (width > INT_MAX / 10 + || (width == INT_MAX / 10 && *f - L_('0') > INT_MAX % 10)) + /* Avoid overflow. */ + width = INT_MAX; + else + { + width *= 10; + width += *f - L_('0'); + } + ++f; + } + while (ISDIGIT (*f)); + } + + /* Check for modifiers. */ + switch (*f) + { + case L_('E'): + case L_('O'): + modifier = *f++; + break; + + default: + modifier = 0; + break; + } + + /* Now do the specified format. */ + format_char = *f; + switch (format_char) + { +#define DO_NUMBER(d, v) \ + digits = d; \ + number_value = v; goto do_number +#define DO_SIGNED_NUMBER(d, negative, v) \ + digits = d; \ + negative_number = negative; \ + u_number_value = v; goto do_signed_number + + /* The mask is not what you might think. + When the ordinal i'th bit is set, insert a colon + before the i'th digit of the time zone representation. */ +#define DO_TZ_OFFSET(d, negative, mask, v) \ + digits = d; \ + negative_number = negative; \ + tz_colon_mask = mask; \ + u_number_value = v; goto do_tz_offset +#define DO_NUMBER_SPACEPAD(d, v) \ + digits = d; \ + number_value = v; goto do_number_spacepad + + case L_('%'): + if (modifier != 0) + goto bad_format; + add1 (*f); + break; + + case L_('a'): + if (modifier != 0) + goto bad_format; + if (change_case) + { + to_uppcase = true; + to_lowcase = false; + } +#ifdef _NL_CURRENT + cpy (aw_len, a_wkday); + break; +#else + goto underlying_strftime; +#endif + + case 'A': + if (modifier != 0) + goto bad_format; + if (change_case) + { + to_uppcase = true; + to_lowcase = false; + } +#ifdef _NL_CURRENT + cpy (STRLEN (f_wkday), f_wkday); + break; +#else + goto underlying_strftime; +#endif + + case L_('b'): + case L_('h'): + if (change_case) + { + to_uppcase = true; + to_lowcase = false; + } + if (modifier != 0) + goto bad_format; +#ifdef _NL_CURRENT + cpy (am_len, a_month); + break; +#else + goto underlying_strftime; +#endif + + case L_('B'): + if (modifier != 0) + goto bad_format; + if (change_case) + { + to_uppcase = true; + to_lowcase = false; + } +#ifdef _NL_CURRENT + cpy (STRLEN (f_month), f_month); + break; +#else + goto underlying_strftime; +#endif + + case L_('c'): + if (modifier == L_('O')) + goto bad_format; +#ifdef _NL_CURRENT + if (! (modifier == 'E' + && (*(subfmt = + (const CHAR_T *) _NL_CURRENT (LC_TIME, + NLW(ERA_D_T_FMT))) + != '\0'))) + subfmt = (const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(D_T_FMT)); +#else + goto underlying_strftime; +#endif + + subformat: + { + size_t len = strftime_case_ (to_uppcase, + NULL, STRFTIME_ARG ((size_t) -1) + subfmt, + tp extra_args LOCALE_ARG); + add (len, strftime_case_ (to_uppcase, p, + STRFTIME_ARG (maxsize - i) + subfmt, + tp extra_args LOCALE_ARG)); + } + break; + +#if !(defined _NL_CURRENT && HAVE_STRUCT_ERA_ENTRY) + underlying_strftime: + { + /* The relevant information is available only via the + underlying strftime implementation, so use that. */ + char ufmt[5]; + char *u = ufmt; + char ubuf[1024]; /* enough for any single format in practice */ + size_t len; + /* Make sure we're calling the actual underlying strftime. + In some cases, config.h contains something like + "#define strftime rpl_strftime". */ +# ifdef strftime +# undef strftime + size_t strftime (); +# endif + + /* The space helps distinguish strftime failure from empty + output. */ + *u++ = ' '; + *u++ = '%'; + if (modifier != 0) + *u++ = modifier; + *u++ = format_char; + *u = '\0'; + len = strftime (ubuf, sizeof ubuf, ufmt, tp); + if (len != 0) + cpy (len - 1, ubuf + 1); + } + break; +#endif + + case L_('C'): + if (modifier == L_('O')) + goto bad_format; + if (modifier == L_('E')) + { +#if HAVE_STRUCT_ERA_ENTRY + struct era_entry *era = _nl_get_era_entry (tp HELPER_LOCALE_ARG); + if (era) + { +# ifdef COMPILE_WIDE + size_t len = __wcslen (era->era_wname); + cpy (len, era->era_wname); +# else + size_t len = strlen (era->era_name); + cpy (len, era->era_name); +# endif + break; + } +#else + goto underlying_strftime; +#endif + } + + { + int century = tp->tm_year / 100 + TM_YEAR_BASE / 100; + century -= tp->tm_year % 100 < 0 && 0 < century; + DO_SIGNED_NUMBER (2, tp->tm_year < - TM_YEAR_BASE, century); + } + + case L_('x'): + if (modifier == L_('O')) + goto bad_format; +#ifdef _NL_CURRENT + if (! (modifier == L_('E') + && (*(subfmt = + (const CHAR_T *)_NL_CURRENT (LC_TIME, NLW(ERA_D_FMT))) + != L_('\0')))) + subfmt = (const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(D_FMT)); + goto subformat; +#else + goto underlying_strftime; +#endif + case L_('D'): + if (modifier != 0) + goto bad_format; + subfmt = L_("%m/%d/%y"); + goto subformat; + + case L_('d'): + if (modifier == L_('E')) + goto bad_format; + + DO_NUMBER (2, tp->tm_mday); + + case L_('e'): + if (modifier == L_('E')) + goto bad_format; + + DO_NUMBER_SPACEPAD (2, tp->tm_mday); + + /* All numeric formats set DIGITS and NUMBER_VALUE (or U_NUMBER_VALUE) + and then jump to one of these labels. */ + + do_tz_offset: + always_output_a_sign = true; + goto do_number_body; + + do_number_spacepad: + /* Force `_' flag unless overridden by `0' or `-' flag. */ + if (pad != L_('0') && pad != L_('-')) + pad = L_('_'); + + do_number: + /* Format NUMBER_VALUE according to the MODIFIER flag. */ + negative_number = number_value < 0; + u_number_value = number_value; + + do_signed_number: + always_output_a_sign = false; + tz_colon_mask = 0; + + do_number_body: + /* Format U_NUMBER_VALUE according to the MODIFIER flag. + NEGATIVE_NUMBER is nonzero if the original number was + negative; in this case it was converted directly to + unsigned int (i.e., modulo (UINT_MAX + 1)) without + negating it. */ + if (modifier == L_('O') && !negative_number) + { +#ifdef _NL_CURRENT + /* Get the locale specific alternate representation of + the number. If none exist NULL is returned. */ + const CHAR_T *cp = nl_get_alt_digit (u_number_value + HELPER_LOCALE_ARG); + + if (cp != NULL) + { + size_t digitlen = STRLEN (cp); + if (digitlen != 0) + { + cpy (digitlen, cp); + break; + } + } +#else + goto underlying_strftime; +#endif + } + + bufp = buf + sizeof (buf) / sizeof (buf[0]); + + if (negative_number) + u_number_value = - u_number_value; + + do + { + if (tz_colon_mask & 1) + *--bufp = ':'; + tz_colon_mask >>= 1; + *--bufp = u_number_value % 10 + L_('0'); + u_number_value /= 10; + } + while (u_number_value != 0 || tz_colon_mask != 0); + + do_number_sign_and_padding: + if (digits < width) + digits = width; + + sign_char = (negative_number ? L_('-') + : always_output_a_sign ? L_('+') + : 0); + + if (pad == L_('-')) + { + if (sign_char) + add1 (sign_char); + } + else + { + int padding = digits - (buf + (sizeof (buf) / sizeof (buf[0])) + - bufp) - !!sign_char; + + if (padding > 0) + { + if (pad == L_('_')) + { + if ((size_t) padding >= maxsize - i) + return 0; + + if (p) + memset_space (p, padding); + i += padding; + width = width > padding ? width - padding : 0; + if (sign_char) + add1 (sign_char); + } + else + { + if ((size_t) digits >= maxsize - i) + return 0; + + if (sign_char) + add1 (sign_char); + + if (p) + memset_zero (p, padding); + i += padding; + width = 0; + } + } + else + { + if (sign_char) + add1 (sign_char); + } + } + + cpy (buf + sizeof (buf) / sizeof (buf[0]) - bufp, bufp); + break; + + case L_('F'): + if (modifier != 0) + goto bad_format; + subfmt = L_("%Y-%m-%d"); + goto subformat; + + case L_('H'): + if (modifier == L_('E')) + goto bad_format; + + DO_NUMBER (2, tp->tm_hour); + + case L_('I'): + if (modifier == L_('E')) + goto bad_format; + + DO_NUMBER (2, hour12); + + case L_('k'): /* GNU extension. */ + if (modifier == L_('E')) + goto bad_format; + + DO_NUMBER_SPACEPAD (2, tp->tm_hour); + + case L_('l'): /* GNU extension. */ + if (modifier == L_('E')) + goto bad_format; + + DO_NUMBER_SPACEPAD (2, hour12); + + case L_('j'): + if (modifier == L_('E')) + goto bad_format; + + DO_SIGNED_NUMBER (3, tp->tm_yday < -1, tp->tm_yday + 1U); + + case L_('M'): + if (modifier == L_('E')) + goto bad_format; + + DO_NUMBER (2, tp->tm_min); + + case L_('m'): + if (modifier == L_('E')) + goto bad_format; + + DO_SIGNED_NUMBER (2, tp->tm_mon < -1, tp->tm_mon + 1U); + +#ifndef _LIBC + case L_('N'): /* GNU extension. */ + if (modifier == L_('E')) + goto bad_format; + + number_value = ns; + if (width == -1) + width = 9; + else + { + /* Take an explicit width less than 9 as a precision. */ + int j; + for (j = width; j < 9; j++) + number_value /= 10; + } + + DO_NUMBER (width, number_value); +#endif + + case L_('n'): + add1 (L_('\n')); + break; + + case L_('P'): + to_lowcase = true; +#ifndef _NL_CURRENT + format_char = L_('p'); +#endif + /* FALLTHROUGH */ + + case L_('p'): + if (change_case) + { + to_uppcase = false; + to_lowcase = true; + } +#ifdef _NL_CURRENT + cpy (ap_len, ampm); + break; +#else + goto underlying_strftime; +#endif + + case L_('R'): + subfmt = L_("%H:%M"); + goto subformat; + + case L_('r'): +#ifdef _NL_CURRENT + if (*(subfmt = (const CHAR_T *) _NL_CURRENT (LC_TIME, + NLW(T_FMT_AMPM))) + == L_('\0')) + subfmt = L_("%I:%M:%S %p"); + goto subformat; +#else + goto underlying_strftime; +#endif + + case L_('S'): + if (modifier == L_('E')) + goto bad_format; + + DO_NUMBER (2, tp->tm_sec); + + case L_('s'): /* GNU extension. */ + { + struct tm ltm; + time_t t; + + ltm = *tp; + t = mktime (<m); + + /* Generate string value for T using time_t arithmetic; + this works even if sizeof (long) < sizeof (time_t). */ + + bufp = buf + sizeof (buf) / sizeof (buf[0]); + negative_number = t < 0; + + do + { + int d = t % 10; + t /= 10; + *--bufp = (negative_number ? -d : d) + L_('0'); + } + while (t != 0); + + digits = 1; + always_output_a_sign = false; + goto do_number_sign_and_padding; + } + + case L_('X'): + if (modifier == L_('O')) + goto bad_format; +#ifdef _NL_CURRENT + if (! (modifier == L_('E') + && (*(subfmt = + (const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(ERA_T_FMT))) + != L_('\0')))) + subfmt = (const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(T_FMT)); + goto subformat; +#else + goto underlying_strftime; +#endif + case L_('T'): + subfmt = L_("%H:%M:%S"); + goto subformat; + + case L_('t'): + add1 (L_('\t')); + break; + + case L_('u'): + DO_NUMBER (1, (tp->tm_wday - 1 + 7) % 7 + 1); + + case L_('U'): + if (modifier == L_('E')) + goto bad_format; + + DO_NUMBER (2, (tp->tm_yday - tp->tm_wday + 7) / 7); + + case L_('V'): + case L_('g'): + case L_('G'): + if (modifier == L_('E')) + goto bad_format; + { + /* YEAR is a leap year if and only if (tp->tm_year + TM_YEAR_BASE) + is a leap year, except that YEAR and YEAR - 1 both work + correctly even when (tp->tm_year + TM_YEAR_BASE) would + overflow. */ + int year = (tp->tm_year + + (tp->tm_year < 0 + ? TM_YEAR_BASE % 400 + : TM_YEAR_BASE % 400 - 400)); + int year_adjust = 0; + int days = iso_week_days (tp->tm_yday, tp->tm_wday); + + if (days < 0) + { + /* This ISO week belongs to the previous year. */ + year_adjust = -1; + days = iso_week_days (tp->tm_yday + (365 + __isleap (year - 1)), + tp->tm_wday); + } + else + { + int d = iso_week_days (tp->tm_yday - (365 + __isleap (year)), + tp->tm_wday); + if (0 <= d) + { + /* This ISO week belongs to the next year. */ + year_adjust = 1; + days = d; + } + } + + switch (*f) + { + case L_('g'): + { + int yy = (tp->tm_year % 100 + year_adjust) % 100; + DO_NUMBER (2, (0 <= yy + ? yy + : tp->tm_year < -TM_YEAR_BASE - year_adjust + ? -yy + : yy + 100)); + } + + case L_('G'): + DO_SIGNED_NUMBER (4, tp->tm_year < -TM_YEAR_BASE - year_adjust, + (tp->tm_year + (unsigned int) TM_YEAR_BASE + + year_adjust)); + + default: + DO_NUMBER (2, days / 7 + 1); + } + } + + case L_('W'): + if (modifier == L_('E')) + goto bad_format; + + DO_NUMBER (2, (tp->tm_yday - (tp->tm_wday - 1 + 7) % 7 + 7) / 7); + + case L_('w'): + if (modifier == L_('E')) + goto bad_format; + + DO_NUMBER (1, tp->tm_wday); + + case L_('Y'): + if (modifier == 'E') + { +#if HAVE_STRUCT_ERA_ENTRY + struct era_entry *era = _nl_get_era_entry (tp HELPER_LOCALE_ARG); + if (era) + { +# ifdef COMPILE_WIDE + subfmt = era->era_wformat; +# else + subfmt = era->era_format; +# endif + goto subformat; + } +#else + goto underlying_strftime; +#endif + } + if (modifier == L_('O')) + goto bad_format; + else + DO_SIGNED_NUMBER (4, tp->tm_year < -TM_YEAR_BASE, + tp->tm_year + (unsigned int) TM_YEAR_BASE); + + case L_('y'): + if (modifier == L_('E')) + { +#if HAVE_STRUCT_ERA_ENTRY + struct era_entry *era = _nl_get_era_entry (tp HELPER_LOCALE_ARG); + if (era) + { + int delta = tp->tm_year - era->start_date[0]; + DO_NUMBER (1, (era->offset + + delta * era->absolute_direction)); + } +#else + goto underlying_strftime; +#endif + } + + { + int yy = tp->tm_year % 100; + if (yy < 0) + yy = tp->tm_year < - TM_YEAR_BASE ? -yy : yy + 100; + DO_NUMBER (2, yy); + } + + case L_('Z'): + if (change_case) + { + to_uppcase = false; + to_lowcase = true; + } + +#if HAVE_TZNAME + /* The tzset() call might have changed the value. */ + if (!(zone && *zone) && tp->tm_isdst >= 0) + zone = tzname[tp->tm_isdst != 0]; +#endif + if (! zone) + zone = ""; + +#ifdef COMPILE_WIDE + { + /* The zone string is always given in multibyte form. We have + to transform it first. */ + wchar_t *wczone; + size_t len; + widen (zone, wczone, len); + cpy (len, wczone); + } +#else + cpy (strlen (zone), zone); +#endif + break; + + case L_(':'): + /* :, ::, and ::: are valid only just before 'z'. + :::: etc. are rejected later. */ + for (colons = 1; f[colons] == L_(':'); colons++) + continue; + if (f[colons] != L_('z')) + goto bad_format; + f += colons; + goto do_z_conversion; + + case L_('z'): + colons = 0; + + do_z_conversion: + if (tp->tm_isdst < 0) + break; + + { + int diff; + int hour_diff; + int min_diff; + int sec_diff; +#if HAVE_TM_GMTOFF + diff = tp->tm_gmtoff; +#else + if (ut) + diff = 0; + else + { + struct tm gtm; + struct tm ltm; + time_t lt; + + ltm = *tp; + lt = mktime (<m); + + if (lt == (time_t) -1) + { + /* mktime returns -1 for errors, but -1 is also a + valid time_t value. Check whether an error really + occurred. */ + struct tm tm; + + if (! __localtime_r (<, &tm) + || ((ltm.tm_sec ^ tm.tm_sec) + | (ltm.tm_min ^ tm.tm_min) + | (ltm.tm_hour ^ tm.tm_hour) + | (ltm.tm_mday ^ tm.tm_mday) + | (ltm.tm_mon ^ tm.tm_mon) + | (ltm.tm_year ^ tm.tm_year))) + break; + } + + if (! __gmtime_r (<, >m)) + break; + + diff = tm_diff (<m, >m); + } +#endif + + hour_diff = diff / 60 / 60; + min_diff = diff / 60 % 60; + sec_diff = diff % 60; + + switch (colons) + { + case 0: /* +hhmm */ + DO_TZ_OFFSET (5, diff < 0, 0, hour_diff * 100 + min_diff); + + case 1: tz_hh_mm: /* +hh:mm */ + DO_TZ_OFFSET (6, diff < 0, 04, hour_diff * 100 + min_diff); + + case 2: tz_hh_mm_ss: /* +hh:mm:ss */ + DO_TZ_OFFSET (9, diff < 0, 024, + hour_diff * 10000 + min_diff * 100 + sec_diff); + + case 3: /* +hh if possible, else +hh:mm, else +hh:mm:ss */ + if (sec_diff != 0) + goto tz_hh_mm_ss; + if (min_diff != 0) + goto tz_hh_mm; + DO_TZ_OFFSET (3, diff < 0, 0, hour_diff); + + default: + goto bad_format; + } + } + + case L_('\0'): /* GNU extension: % at end of format. */ + --f; + /* Fall through. */ + default: + /* Unknown format; output the format, including the '%', + since this is most likely the right thing to do if a + multibyte string has been misparsed. */ + bad_format: + { + int flen; + for (flen = 1; f[1 - flen] != L_('%'); flen++) + continue; + cpy (flen, &f[1 - flen]); + } + break; + } + } + +#if ! FPRINTFTIME + if (p && maxsize != 0) + *p = L_('\0'); +#endif + + return i; +} + +/* Write information from TP into S according to the format + string FORMAT, writing no more that MAXSIZE characters + (including the terminating '\0') and returning number of + characters written. If S is NULL, nothing will be written + anywhere, so to determine how many characters would be + written, use NULL for S and (size_t) -1 for MAXSIZE. */ +size_t +my_strftime (STREAM_OR_CHAR_T *s, STRFTIME_ARG (size_t maxsize) + const CHAR_T *format, + const struct tm *tp extra_args_spec LOCALE_PARAM_PROTO) +{ + return strftime_case_ (false, s, STRFTIME_ARG (maxsize) + format, tp extra_args LOCALE_ARG); +} + +#if defined _LIBC && ! FPRINTFTIME +libc_hidden_def (my_strftime) +#endif + + +#if defined emacs && ! FPRINTFTIME +/* For Emacs we have a separate interface which corresponds to the normal + strftime function plus the ut argument, but without the ns argument. */ +size_t +emacs_strftimeu (char *s, size_t maxsize, const char *format, + const struct tm *tp, int ut) +{ + return my_strftime (s, maxsize, format, tp, ut, 0); +} +#endif diff --git a/src/bin/findutils/gnulib/lib/strftime.h b/src/bin/findutils/gnulib/lib/strftime.h new file mode 100644 index 0000000000..ae9cc6b2dd --- /dev/null +++ b/src/bin/findutils/gnulib/lib/strftime.h @@ -0,0 +1,20 @@ +/* declarations for strftime.c + + Copyright (C) 2002, 2004 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +size_t nstrftime (char *, size_t, char const *, struct tm const *, int, int); diff --git a/src/bin/findutils/gnulib/lib/string.h b/src/bin/findutils/gnulib/lib/string.h new file mode 100644 index 0000000000..1e0283d0a8 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/string.h @@ -0,0 +1,549 @@ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +/* A GNU-like . + + Copyright (C) 1995-1996, 2001-2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _GL_STRING_H + +/* The include_next requires a split double-inclusion guard. */ +#include_next + +#ifndef _GL_STRING_H +#define _GL_STRING_H + + +/* The definition of GL_LINK_WARNING is copied here. */ +/* GL_LINK_WARNING("literal string") arranges to emit the literal string as + a linker warning on most glibc systems. + We use a linker warning rather than a preprocessor warning, because + #warning cannot be used inside macros. */ +#ifndef GL_LINK_WARNING + /* This works on platforms with GNU ld and ELF object format. + Testing __GLIBC__ is sufficient for asserting that GNU ld is in use. + Testing __ELF__ guarantees the ELF object format. + Testing __GNUC__ is necessary for the compound expression syntax. */ +# if defined __GLIBC__ && defined __ELF__ && defined __GNUC__ +# define GL_LINK_WARNING(message) \ + GL_LINK_WARNING1 (__FILE__, __LINE__, message) +# define GL_LINK_WARNING1(file, line, message) \ + GL_LINK_WARNING2 (file, line, message) /* macroexpand file and line */ +# define GL_LINK_WARNING2(file, line, message) \ + GL_LINK_WARNING3 (file ":" #line ": warning: " message) +# define GL_LINK_WARNING3(message) \ + ({ static const char warning[sizeof (message)] \ + __attribute__ ((__unused__, \ + __section__ (".gnu.warning"), \ + __aligned__ (1))) \ + = message "\n"; \ + (void)0; \ + }) +# else +# define GL_LINK_WARNING(message) ((void) 0) +# endif +#endif + + +#ifdef __cplusplus +extern "C" { +#endif + + +/* Return the first occurrence of NEEDLE in HAYSTACK. */ +#if 0 +# if ! 1 +extern void *memmem (void const *__haystack, size_t __haystack_len, + void const *__needle, size_t __needle_len); +# endif +#elif defined GNULIB_POSIXCHECK +# undef memmem +# define memmem(a,al,b,bl) \ + (GL_LINK_WARNING ("memmem is unportable - " \ + "use gnulib module memmem for portability"), \ + memmem (a, al, b, bl)) +#endif + +/* Copy N bytes of SRC to DEST, return pointer to bytes after the + last written byte. */ +#if 1 +# if ! 0 +extern void *mempcpy (void *restrict __dest, void const *restrict __src, + size_t __n); +# endif +#elif defined GNULIB_POSIXCHECK +# undef mempcpy +# define mempcpy(a,b,n) \ + (GL_LINK_WARNING ("mempcpy is unportable - " \ + "use gnulib module mempcpy for portability"), \ + mempcpy (a, b, n)) +#endif + +/* Search backwards through a block for a byte (specified as an int). */ +#if 1 +# if ! 0 +extern void *memrchr (void const *, int, size_t); +# endif +#elif defined GNULIB_POSIXCHECK +# undef memrchr +# define memrchr(a,b,c) \ + (GL_LINK_WARNING ("memrchr is unportable - " \ + "use gnulib module memrchr for portability"), \ + memrchr (a, b, c)) +#endif + +/* Copy SRC to DST, returning the address of the terminating '\0' in DST. */ +#if 1 +# if ! 1 +extern char *stpcpy (char *restrict __dst, char const *restrict __src); +# endif +#elif defined GNULIB_POSIXCHECK +# undef stpcpy +# define stpcpy(a,b) \ + (GL_LINK_WARNING ("stpcpy is unportable - " \ + "use gnulib module stpcpy for portability"), \ + stpcpy (a, b)) +#endif + +/* Copy no more than N bytes of SRC to DST, returning a pointer past the + last non-NUL byte written into DST. */ +#if 0 +# if ! 1 +# define stpncpy gnu_stpncpy +extern char *stpncpy (char *restrict __dst, char const *restrict __src, + size_t __n); +# endif +#elif defined GNULIB_POSIXCHECK +# undef stpncpy +# define stpncpy(a,b,n) \ + (GL_LINK_WARNING ("stpncpy is unportable - " \ + "use gnulib module stpncpy for portability"), \ + stpncpy (a, b, n)) +#endif + +#if defined GNULIB_POSIXCHECK +/* strchr() does not work with multibyte strings if the locale encoding is + GB18030 and the character to be searched is a digit. */ +# undef strchr +# define strchr(s,c) \ + (GL_LINK_WARNING ("strchr cannot work correctly on character strings " \ + "in some multibyte locales - " \ + "use mbschr if you care about internationalization"), \ + strchr (s, c)) +#endif + +/* Find the first occurrence of C in S or the final NUL byte. */ +#if 0 +# if ! 1 +extern char *strchrnul (char const *__s, int __c_in); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strchrnul +# define strchrnul(a,b) \ + (GL_LINK_WARNING ("strchrnul is unportable - " \ + "use gnulib module strchrnul for portability"), \ + strchrnul (a, b)) +#endif + +/* Duplicate S, returning an identical malloc'd string. */ +#if 1 +# if ! 1 && ! defined strdup +extern char *strdup (char const *__s); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strdup +# define strdup(a) \ + (GL_LINK_WARNING ("strdup is unportable - " \ + "use gnulib module strdup for portability"), \ + strdup (a)) +#endif + +/* Return a newly allocated copy of at most N bytes of STRING. */ +#if 1 +# if ! 0 +# undef strndup +# define strndup rpl_strndup +# endif +# if ! 0 || ! 0 +extern char *strndup (char const *__string, size_t __n); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strndup +# define strndup(a,n) \ + (GL_LINK_WARNING ("strndup is unportable - " \ + "use gnulib module strndup for portability"), \ + strndup (a, n)) +#endif + +/* Find the length (number of bytes) of STRING, but scan at most + MAXLEN bytes. If no '\0' terminator is found in that many bytes, + return MAXLEN. */ +#if 1 +# if ! 1 +extern size_t strnlen (char const *__string, size_t __maxlen); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strnlen +# define strnlen(a,n) \ + (GL_LINK_WARNING ("strnlen is unportable - " \ + "use gnulib module strnlen for portability"), \ + strnlen (a, n)) +#endif + +#if defined GNULIB_POSIXCHECK +/* strcspn() assumes the second argument is a list of single-byte characters. + Even in this simple case, it does not work with multibyte strings if the + locale encoding is GB18030 and one of the characters to be searched is a + digit. */ +# undef strcspn +# define strcspn(s,a) \ + (GL_LINK_WARNING ("strcspn cannot work correctly on character strings " \ + "in multibyte locales - " \ + "use mbscspn if you care about internationalization"), \ + strcspn (s, a)) +#endif + +/* Find the first occurrence in S of any character in ACCEPT. */ +#if 0 +# if ! 1 +extern char *strpbrk (char const *__s, char const *__accept); +# endif +# if defined GNULIB_POSIXCHECK +/* strpbrk() assumes the second argument is a list of single-byte characters. + Even in this simple case, it does not work with multibyte strings if the + locale encoding is GB18030 and one of the characters to be searched is a + digit. */ +# undef strpbrk +# define strpbrk(s,a) \ + (GL_LINK_WARNING ("strpbrk cannot work correctly on character strings " \ + "in multibyte locales - " \ + "use mbspbrk if you care about internationalization"), \ + strpbrk (s, a)) +# endif +#elif defined GNULIB_POSIXCHECK +# undef strpbrk +# define strpbrk(s,a) \ + (GL_LINK_WARNING ("strpbrk is unportable - " \ + "use gnulib module strpbrk for portability"), \ + strpbrk (s, a)) +#endif + +#if defined GNULIB_POSIXCHECK +/* strspn() assumes the second argument is a list of single-byte characters. + Even in this simple case, it cannot work with multibyte strings. */ +# undef strspn +# define strspn(s,a) \ + (GL_LINK_WARNING ("strspn cannot work correctly on character strings " \ + "in multibyte locales - " \ + "use mbsspn if you care about internationalization"), \ + strspn (s, a)) +#endif + +#if defined GNULIB_POSIXCHECK +/* strrchr() does not work with multibyte strings if the locale encoding is + GB18030 and the character to be searched is a digit. */ +# undef strrchr +# define strrchr(s,c) \ + (GL_LINK_WARNING ("strrchr cannot work correctly on character strings " \ + "in some multibyte locales - " \ + "use mbsrchr if you care about internationalization"), \ + strrchr (s, c)) +#endif + +/* Search the next delimiter (char listed in DELIM) starting at *STRINGP. + If one is found, overwrite it with a NUL, and advance *STRINGP + to point to the next char after it. Otherwise, set *STRINGP to NULL. + If *STRINGP was already NULL, nothing happens. + Return the old value of *STRINGP. + + This is a variant of strtok() that is multithread-safe and supports + empty fields. + + Caveat: It modifies the original string. + Caveat: These functions cannot be used on constant strings. + Caveat: The identity of the delimiting character is lost. + Caveat: It doesn't work with multibyte strings unless all of the delimiter + characters are ASCII characters < 0x30. + + See also strtok_r(). */ +#if 0 +# if ! 1 +extern char *strsep (char **restrict __stringp, char const *restrict __delim); +# endif +# if defined GNULIB_POSIXCHECK +# undef strsep +# define strsep(s,d) \ + (GL_LINK_WARNING ("strsep cannot work correctly on character strings " \ + "in multibyte locales - " \ + "use mbssep if you care about internationalization"), \ + strsep (s, d)) +# endif +#elif defined GNULIB_POSIXCHECK +# undef strsep +# define strsep(s,d) \ + (GL_LINK_WARNING ("strsep is unportable - " \ + "use gnulib module strsep for portability"), \ + strsep (s, d)) +#endif + +#if defined GNULIB_POSIXCHECK +/* strstr() does not work with multibyte strings if the locale encoding is + different from UTF-8: + POSIX says that it operates on "strings", and "string" in POSIX is defined + as a sequence of bytes, not of characters. */ +# undef strstr +# define strstr(a,b) \ + (GL_LINK_WARNING ("strstr cannot work correctly on character strings " \ + "in most multibyte locales - " \ + "use mbsstr if you care about internationalization"), \ + strstr (a, b)) +#endif + +/* Find the first occurrence of NEEDLE in HAYSTACK, using case-insensitive + comparison. */ +#if ! 1 +extern char *strcasestr (const char *haystack, const char *needle); +#endif +#if defined GNULIB_POSIXCHECK +/* strcasestr() does not work with multibyte strings: + It is a glibc extension, and glibc implements it only for unibyte + locales. */ +# undef strcasestr +# define strcasestr(a,b) \ + (GL_LINK_WARNING ("strcasestr does work correctly on character strings " \ + "in multibyte locales - " \ + "use mbscasestr if you care about " \ + "internationalization, or use c-strcasestr if you want " \ + "a locale independent function"), \ + strcasestr (a, b)) +#endif + +/* Parse S into tokens separated by characters in DELIM. + If S is NULL, the saved pointer in SAVE_PTR is used as + the next starting point. For example: + char s[] = "-abc-=-def"; + char *sp; + x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def" + x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL + x = strtok_r(NULL, "=", &sp); // x = NULL + // s = "abc\0-def\0" + + This is a variant of strtok() that is multithread-safe. + + For the POSIX documentation for this function, see: + http://www.opengroup.org/susv3xsh/strtok.html + + Caveat: It modifies the original string. + Caveat: These functions cannot be used on constant strings. + Caveat: The identity of the delimiting character is lost. + Caveat: It doesn't work with multibyte strings unless all of the delimiter + characters are ASCII characters < 0x30. + + See also strsep(). */ +#if 0 +# if ! 1 +extern char *strtok_r (char *restrict s, char const *restrict delim, + char **restrict save_ptr); +# endif +# if defined GNULIB_POSIXCHECK +# undef strtok_r +# define strtok_r(s,d,p) \ + (GL_LINK_WARNING ("strtok_r cannot work correctly on character strings " \ + "in multibyte locales - " \ + "use mbstok_r if you care about internationalization"), \ + strtok_r (s, d, p)) +# endif +#elif defined GNULIB_POSIXCHECK +# undef strtok_r +# define strtok_r(s,d,p) \ + (GL_LINK_WARNING ("strtok_r is unportable - " \ + "use gnulib module strtok_r for portability"), \ + strtok_r (s, d, p)) +#endif + + +/* The following functions are not specified by POSIX. They are gnulib + extensions. */ + +#if 0 +/* Return the number of multibyte characters in the character string STRING. + This considers multibyte characters, unlike strlen, which counts bytes. */ +extern size_t mbslen (const char *string); +#endif + +#if 0 +/* Return the number of multibyte characters in the character string starting + at STRING and ending at STRING + LEN. */ +extern size_t mbsnlen (const char *string, size_t len); +#endif + +#if 0 +/* Locate the first single-byte character C in the character string STRING, + and return a pointer to it. Return NULL if C is not found in STRING. + Unlike strchr(), this function works correctly in multibyte locales with + encodings such as GB18030. */ +# define mbschr rpl_mbschr /* avoid collision with HP-UX function */ +extern char * mbschr (const char *string, int c); +#endif + +#if 0 +/* Locate the last single-byte character C in the character string STRING, + and return a pointer to it. Return NULL if C is not found in STRING. + Unlike strrchr(), this function works correctly in multibyte locales with + encodings such as GB18030. */ +# define mbsrchr rpl_mbsrchr /* avoid collision with HP-UX function */ +extern char * mbsrchr (const char *string, int c); +#endif + +#if 0 +/* Find the first occurrence of the character string NEEDLE in the character + string HAYSTACK. Return NULL if NEEDLE is not found in HAYSTACK. + Unlike strstr(), this function works correctly in multibyte locales with + encodings different from UTF-8. */ +extern char * mbsstr (const char *haystack, const char *needle); +#endif + +#if 0 +/* Compare the character strings S1 and S2, ignoring case, returning less than, + equal to or greater than zero if S1 is lexicographically less than, equal to + or greater than S2. + Note: This function may, in multibyte locales, return 0 for strings of + different lengths! + Unlike strcasecmp(), this function works correctly in multibyte locales. */ +extern int mbscasecmp (const char *s1, const char *s2); +#endif + +#if 0 +/* Compare the initial segment of the character string S1 consisting of at most + N characters with the initial segment of the character string S2 consisting + of at most N characters, ignoring case, returning less than, equal to or + greater than zero if the initial segment of S1 is lexicographically less + than, equal to or greater than the initial segment of S2. + Note: This function may, in multibyte locales, return 0 for initial segments + of different lengths! + Unlike strncasecmp(), this function works correctly in multibyte locales. + But beware that N is not a byte count but a character count! */ +extern int mbsncasecmp (const char *s1, const char *s2, size_t n); +#endif + +#if 0 +/* Compare the initial segment of the character string STRING consisting of + at most mbslen (PREFIX) characters with the character string PREFIX, + ignoring case, returning less than, equal to or greater than zero if this + initial segment is lexicographically less than, equal to or greater than + PREFIX. + Note: This function may, in multibyte locales, return 0 if STRING is of + smaller length than PREFIX! + Unlike strncasecmp(), this function works correctly in multibyte + locales. */ +extern char * mbspcasecmp (const char *string, const char *prefix); +#endif + +#if 0 +/* Find the first occurrence of the character string NEEDLE in the character + string HAYSTACK, using case-insensitive comparison. + Note: This function may, in multibyte locales, return success even if + strlen (haystack) < strlen (needle) ! + Unlike strcasestr(), this function works correctly in multibyte locales. */ +extern char * mbscasestr (const char *haystack, const char *needle); +#endif + +#if 0 +/* Find the first occurrence in the character string STRING of any character + in the character string ACCEPT. Return the number of bytes from the + beginning of the string to this occurrence, or to the end of the string + if none exists. + Unlike strcspn(), this function works correctly in multibyte locales. */ +extern size_t mbscspn (const char *string, const char *accept); +#endif + +#if 0 +/* Find the first occurrence in the character string STRING of any character + in the character string ACCEPT. Return the pointer to it, or NULL if none + exists. + Unlike strpbrk(), this function works correctly in multibyte locales. */ +# define mbspbrk rpl_mbspbrk /* avoid collision with HP-UX function */ +extern char * mbspbrk (const char *string, const char *accept); +#endif + +#if 0 +/* Find the first occurrence in the character string STRING of any character + not in the character string REJECT. Return the number of bytes from the + beginning of the string to this occurrence, or to the end of the string + if none exists. + Unlike strspn(), this function works correctly in multibyte locales. */ +extern size_t mbsspn (const char *string, const char *reject); +#endif + +#if 0 +/* Search the next delimiter (multibyte character listed in the character + string DELIM) starting at the character string *STRINGP. + If one is found, overwrite it with a NUL, and advance *STRINGP to point + to the next multibyte character after it. Otherwise, set *STRINGP to NULL. + If *STRINGP was already NULL, nothing happens. + Return the old value of *STRINGP. + + This is a variant of mbstok_r() that supports empty fields. + + Caveat: It modifies the original string. + Caveat: These functions cannot be used on constant strings. + Caveat: The identity of the delimiting character is lost. + + See also mbstok_r(). */ +extern char * mbssep (char **stringp, const char *delim); +#endif + +#if 0 +/* Parse the character string STRING into tokens separated by characters in + the character string DELIM. + If STRING is NULL, the saved pointer in SAVE_PTR is used as + the next starting point. For example: + char s[] = "-abc-=-def"; + char *sp; + x = mbstok_r(s, "-", &sp); // x = "abc", sp = "=-def" + x = mbstok_r(NULL, "-=", &sp); // x = "def", sp = NULL + x = mbstok_r(NULL, "=", &sp); // x = NULL + // s = "abc\0-def\0" + + Caveat: It modifies the original string. + Caveat: These functions cannot be used on constant strings. + Caveat: The identity of the delimiting character is lost. + + See also mbssep(). */ +extern char * mbstok_r (char *string, const char *delim, char **save_ptr); +#endif + +/* Map any int, typically from errno, into an error message. */ +#if 1 +# if 0 +# undef strerror +# define strerror rpl_strerror +extern char *strerror (int); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strerror +# define strerror(e) \ + (GL_LINK_WARNING ("strerror is unportable - " \ + "use gnulib module strerror to guarantee non-NULL result"), \ + strerror (e)) +#endif + + +#ifdef __cplusplus +} +#endif + +#endif /* _GL_STRING_H */ +#endif /* _GL_STRING_H */ diff --git a/src/bin/findutils/gnulib/lib/string.in.h b/src/bin/findutils/gnulib/lib/string.in.h new file mode 100644 index 0000000000..f1cf99f38b --- /dev/null +++ b/src/bin/findutils/gnulib/lib/string.in.h @@ -0,0 +1,520 @@ +/* A GNU-like . + + Copyright (C) 1995-1996, 2001-2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _GL_STRING_H + +/* The include_next requires a split double-inclusion guard. */ +#@INCLUDE_NEXT@ @NEXT_STRING_H@ + +#ifndef _GL_STRING_H +#define _GL_STRING_H + + +/* The definition of GL_LINK_WARNING is copied here. */ + + +#ifdef __cplusplus +extern "C" { +#endif + + +/* Return the first occurrence of NEEDLE in HAYSTACK. */ +#if @GNULIB_MEMMEM@ +# if ! @HAVE_DECL_MEMMEM@ +extern void *memmem (void const *__haystack, size_t __haystack_len, + void const *__needle, size_t __needle_len); +# endif +#elif defined GNULIB_POSIXCHECK +# undef memmem +# define memmem(a,al,b,bl) \ + (GL_LINK_WARNING ("memmem is unportable - " \ + "use gnulib module memmem for portability"), \ + memmem (a, al, b, bl)) +#endif + +/* Copy N bytes of SRC to DEST, return pointer to bytes after the + last written byte. */ +#if @GNULIB_MEMPCPY@ +# if ! @HAVE_MEMPCPY@ +extern void *mempcpy (void *restrict __dest, void const *restrict __src, + size_t __n); +# endif +#elif defined GNULIB_POSIXCHECK +# undef mempcpy +# define mempcpy(a,b,n) \ + (GL_LINK_WARNING ("mempcpy is unportable - " \ + "use gnulib module mempcpy for portability"), \ + mempcpy (a, b, n)) +#endif + +/* Search backwards through a block for a byte (specified as an int). */ +#if @GNULIB_MEMRCHR@ +# if ! @HAVE_DECL_MEMRCHR@ +extern void *memrchr (void const *, int, size_t); +# endif +#elif defined GNULIB_POSIXCHECK +# undef memrchr +# define memrchr(a,b,c) \ + (GL_LINK_WARNING ("memrchr is unportable - " \ + "use gnulib module memrchr for portability"), \ + memrchr (a, b, c)) +#endif + +/* Copy SRC to DST, returning the address of the terminating '\0' in DST. */ +#if @GNULIB_STPCPY@ +# if ! @HAVE_STPCPY@ +extern char *stpcpy (char *restrict __dst, char const *restrict __src); +# endif +#elif defined GNULIB_POSIXCHECK +# undef stpcpy +# define stpcpy(a,b) \ + (GL_LINK_WARNING ("stpcpy is unportable - " \ + "use gnulib module stpcpy for portability"), \ + stpcpy (a, b)) +#endif + +/* Copy no more than N bytes of SRC to DST, returning a pointer past the + last non-NUL byte written into DST. */ +#if @GNULIB_STPNCPY@ +# if ! @HAVE_STPNCPY@ +# define stpncpy gnu_stpncpy +extern char *stpncpy (char *restrict __dst, char const *restrict __src, + size_t __n); +# endif +#elif defined GNULIB_POSIXCHECK +# undef stpncpy +# define stpncpy(a,b,n) \ + (GL_LINK_WARNING ("stpncpy is unportable - " \ + "use gnulib module stpncpy for portability"), \ + stpncpy (a, b, n)) +#endif + +#if defined GNULIB_POSIXCHECK +/* strchr() does not work with multibyte strings if the locale encoding is + GB18030 and the character to be searched is a digit. */ +# undef strchr +# define strchr(s,c) \ + (GL_LINK_WARNING ("strchr cannot work correctly on character strings " \ + "in some multibyte locales - " \ + "use mbschr if you care about internationalization"), \ + strchr (s, c)) +#endif + +/* Find the first occurrence of C in S or the final NUL byte. */ +#if @GNULIB_STRCHRNUL@ +# if ! @HAVE_STRCHRNUL@ +extern char *strchrnul (char const *__s, int __c_in); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strchrnul +# define strchrnul(a,b) \ + (GL_LINK_WARNING ("strchrnul is unportable - " \ + "use gnulib module strchrnul for portability"), \ + strchrnul (a, b)) +#endif + +/* Duplicate S, returning an identical malloc'd string. */ +#if @GNULIB_STRDUP@ +# if ! @HAVE_DECL_STRDUP@ && ! defined strdup +extern char *strdup (char const *__s); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strdup +# define strdup(a) \ + (GL_LINK_WARNING ("strdup is unportable - " \ + "use gnulib module strdup for portability"), \ + strdup (a)) +#endif + +/* Return a newly allocated copy of at most N bytes of STRING. */ +#if @GNULIB_STRNDUP@ +# if ! @HAVE_STRNDUP@ +# undef strndup +# define strndup rpl_strndup +# endif +# if ! @HAVE_STRNDUP@ || ! @HAVE_DECL_STRNDUP@ +extern char *strndup (char const *__string, size_t __n); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strndup +# define strndup(a,n) \ + (GL_LINK_WARNING ("strndup is unportable - " \ + "use gnulib module strndup for portability"), \ + strndup (a, n)) +#endif + +/* Find the length (number of bytes) of STRING, but scan at most + MAXLEN bytes. If no '\0' terminator is found in that many bytes, + return MAXLEN. */ +#if @GNULIB_STRNLEN@ +# if ! @HAVE_DECL_STRNLEN@ +extern size_t strnlen (char const *__string, size_t __maxlen); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strnlen +# define strnlen(a,n) \ + (GL_LINK_WARNING ("strnlen is unportable - " \ + "use gnulib module strnlen for portability"), \ + strnlen (a, n)) +#endif + +#if defined GNULIB_POSIXCHECK +/* strcspn() assumes the second argument is a list of single-byte characters. + Even in this simple case, it does not work with multibyte strings if the + locale encoding is GB18030 and one of the characters to be searched is a + digit. */ +# undef strcspn +# define strcspn(s,a) \ + (GL_LINK_WARNING ("strcspn cannot work correctly on character strings " \ + "in multibyte locales - " \ + "use mbscspn if you care about internationalization"), \ + strcspn (s, a)) +#endif + +/* Find the first occurrence in S of any character in ACCEPT. */ +#if @GNULIB_STRPBRK@ +# if ! @HAVE_STRPBRK@ +extern char *strpbrk (char const *__s, char const *__accept); +# endif +# if defined GNULIB_POSIXCHECK +/* strpbrk() assumes the second argument is a list of single-byte characters. + Even in this simple case, it does not work with multibyte strings if the + locale encoding is GB18030 and one of the characters to be searched is a + digit. */ +# undef strpbrk +# define strpbrk(s,a) \ + (GL_LINK_WARNING ("strpbrk cannot work correctly on character strings " \ + "in multibyte locales - " \ + "use mbspbrk if you care about internationalization"), \ + strpbrk (s, a)) +# endif +#elif defined GNULIB_POSIXCHECK +# undef strpbrk +# define strpbrk(s,a) \ + (GL_LINK_WARNING ("strpbrk is unportable - " \ + "use gnulib module strpbrk for portability"), \ + strpbrk (s, a)) +#endif + +#if defined GNULIB_POSIXCHECK +/* strspn() assumes the second argument is a list of single-byte characters. + Even in this simple case, it cannot work with multibyte strings. */ +# undef strspn +# define strspn(s,a) \ + (GL_LINK_WARNING ("strspn cannot work correctly on character strings " \ + "in multibyte locales - " \ + "use mbsspn if you care about internationalization"), \ + strspn (s, a)) +#endif + +#if defined GNULIB_POSIXCHECK +/* strrchr() does not work with multibyte strings if the locale encoding is + GB18030 and the character to be searched is a digit. */ +# undef strrchr +# define strrchr(s,c) \ + (GL_LINK_WARNING ("strrchr cannot work correctly on character strings " \ + "in some multibyte locales - " \ + "use mbsrchr if you care about internationalization"), \ + strrchr (s, c)) +#endif + +/* Search the next delimiter (char listed in DELIM) starting at *STRINGP. + If one is found, overwrite it with a NUL, and advance *STRINGP + to point to the next char after it. Otherwise, set *STRINGP to NULL. + If *STRINGP was already NULL, nothing happens. + Return the old value of *STRINGP. + + This is a variant of strtok() that is multithread-safe and supports + empty fields. + + Caveat: It modifies the original string. + Caveat: These functions cannot be used on constant strings. + Caveat: The identity of the delimiting character is lost. + Caveat: It doesn't work with multibyte strings unless all of the delimiter + characters are ASCII characters < 0x30. + + See also strtok_r(). */ +#if @GNULIB_STRSEP@ +# if ! @HAVE_STRSEP@ +extern char *strsep (char **restrict __stringp, char const *restrict __delim); +# endif +# if defined GNULIB_POSIXCHECK +# undef strsep +# define strsep(s,d) \ + (GL_LINK_WARNING ("strsep cannot work correctly on character strings " \ + "in multibyte locales - " \ + "use mbssep if you care about internationalization"), \ + strsep (s, d)) +# endif +#elif defined GNULIB_POSIXCHECK +# undef strsep +# define strsep(s,d) \ + (GL_LINK_WARNING ("strsep is unportable - " \ + "use gnulib module strsep for portability"), \ + strsep (s, d)) +#endif + +#if defined GNULIB_POSIXCHECK +/* strstr() does not work with multibyte strings if the locale encoding is + different from UTF-8: + POSIX says that it operates on "strings", and "string" in POSIX is defined + as a sequence of bytes, not of characters. */ +# undef strstr +# define strstr(a,b) \ + (GL_LINK_WARNING ("strstr cannot work correctly on character strings " \ + "in most multibyte locales - " \ + "use mbsstr if you care about internationalization"), \ + strstr (a, b)) +#endif + +/* Find the first occurrence of NEEDLE in HAYSTACK, using case-insensitive + comparison. */ +#if ! @HAVE_STRCASESTR@ +extern char *strcasestr (const char *haystack, const char *needle); +#endif +#if defined GNULIB_POSIXCHECK +/* strcasestr() does not work with multibyte strings: + It is a glibc extension, and glibc implements it only for unibyte + locales. */ +# undef strcasestr +# define strcasestr(a,b) \ + (GL_LINK_WARNING ("strcasestr does work correctly on character strings " \ + "in multibyte locales - " \ + "use mbscasestr if you care about " \ + "internationalization, or use c-strcasestr if you want " \ + "a locale independent function"), \ + strcasestr (a, b)) +#endif + +/* Parse S into tokens separated by characters in DELIM. + If S is NULL, the saved pointer in SAVE_PTR is used as + the next starting point. For example: + char s[] = "-abc-=-def"; + char *sp; + x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def" + x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL + x = strtok_r(NULL, "=", &sp); // x = NULL + // s = "abc\0-def\0" + + This is a variant of strtok() that is multithread-safe. + + For the POSIX documentation for this function, see: + http://www.opengroup.org/susv3xsh/strtok.html + + Caveat: It modifies the original string. + Caveat: These functions cannot be used on constant strings. + Caveat: The identity of the delimiting character is lost. + Caveat: It doesn't work with multibyte strings unless all of the delimiter + characters are ASCII characters < 0x30. + + See also strsep(). */ +#if @GNULIB_STRTOK_R@ +# if ! @HAVE_DECL_STRTOK_R@ +extern char *strtok_r (char *restrict s, char const *restrict delim, + char **restrict save_ptr); +# endif +# if defined GNULIB_POSIXCHECK +# undef strtok_r +# define strtok_r(s,d,p) \ + (GL_LINK_WARNING ("strtok_r cannot work correctly on character strings " \ + "in multibyte locales - " \ + "use mbstok_r if you care about internationalization"), \ + strtok_r (s, d, p)) +# endif +#elif defined GNULIB_POSIXCHECK +# undef strtok_r +# define strtok_r(s,d,p) \ + (GL_LINK_WARNING ("strtok_r is unportable - " \ + "use gnulib module strtok_r for portability"), \ + strtok_r (s, d, p)) +#endif + + +/* The following functions are not specified by POSIX. They are gnulib + extensions. */ + +#if @GNULIB_MBSLEN@ +/* Return the number of multibyte characters in the character string STRING. + This considers multibyte characters, unlike strlen, which counts bytes. */ +extern size_t mbslen (const char *string); +#endif + +#if @GNULIB_MBSNLEN@ +/* Return the number of multibyte characters in the character string starting + at STRING and ending at STRING + LEN. */ +extern size_t mbsnlen (const char *string, size_t len); +#endif + +#if @GNULIB_MBSCHR@ +/* Locate the first single-byte character C in the character string STRING, + and return a pointer to it. Return NULL if C is not found in STRING. + Unlike strchr(), this function works correctly in multibyte locales with + encodings such as GB18030. */ +# define mbschr rpl_mbschr /* avoid collision with HP-UX function */ +extern char * mbschr (const char *string, int c); +#endif + +#if @GNULIB_MBSRCHR@ +/* Locate the last single-byte character C in the character string STRING, + and return a pointer to it. Return NULL if C is not found in STRING. + Unlike strrchr(), this function works correctly in multibyte locales with + encodings such as GB18030. */ +# define mbsrchr rpl_mbsrchr /* avoid collision with HP-UX function */ +extern char * mbsrchr (const char *string, int c); +#endif + +#if @GNULIB_MBSSTR@ +/* Find the first occurrence of the character string NEEDLE in the character + string HAYSTACK. Return NULL if NEEDLE is not found in HAYSTACK. + Unlike strstr(), this function works correctly in multibyte locales with + encodings different from UTF-8. */ +extern char * mbsstr (const char *haystack, const char *needle); +#endif + +#if @GNULIB_MBSCASECMP@ +/* Compare the character strings S1 and S2, ignoring case, returning less than, + equal to or greater than zero if S1 is lexicographically less than, equal to + or greater than S2. + Note: This function may, in multibyte locales, return 0 for strings of + different lengths! + Unlike strcasecmp(), this function works correctly in multibyte locales. */ +extern int mbscasecmp (const char *s1, const char *s2); +#endif + +#if @GNULIB_MBSNCASECMP@ +/* Compare the initial segment of the character string S1 consisting of at most + N characters with the initial segment of the character string S2 consisting + of at most N characters, ignoring case, returning less than, equal to or + greater than zero if the initial segment of S1 is lexicographically less + than, equal to or greater than the initial segment of S2. + Note: This function may, in multibyte locales, return 0 for initial segments + of different lengths! + Unlike strncasecmp(), this function works correctly in multibyte locales. + But beware that N is not a byte count but a character count! */ +extern int mbsncasecmp (const char *s1, const char *s2, size_t n); +#endif + +#if @GNULIB_MBSPCASECMP@ +/* Compare the initial segment of the character string STRING consisting of + at most mbslen (PREFIX) characters with the character string PREFIX, + ignoring case, returning less than, equal to or greater than zero if this + initial segment is lexicographically less than, equal to or greater than + PREFIX. + Note: This function may, in multibyte locales, return 0 if STRING is of + smaller length than PREFIX! + Unlike strncasecmp(), this function works correctly in multibyte + locales. */ +extern char * mbspcasecmp (const char *string, const char *prefix); +#endif + +#if @GNULIB_MBSCASESTR@ +/* Find the first occurrence of the character string NEEDLE in the character + string HAYSTACK, using case-insensitive comparison. + Note: This function may, in multibyte locales, return success even if + strlen (haystack) < strlen (needle) ! + Unlike strcasestr(), this function works correctly in multibyte locales. */ +extern char * mbscasestr (const char *haystack, const char *needle); +#endif + +#if @GNULIB_MBSCSPN@ +/* Find the first occurrence in the character string STRING of any character + in the character string ACCEPT. Return the number of bytes from the + beginning of the string to this occurrence, or to the end of the string + if none exists. + Unlike strcspn(), this function works correctly in multibyte locales. */ +extern size_t mbscspn (const char *string, const char *accept); +#endif + +#if @GNULIB_MBSPBRK@ +/* Find the first occurrence in the character string STRING of any character + in the character string ACCEPT. Return the pointer to it, or NULL if none + exists. + Unlike strpbrk(), this function works correctly in multibyte locales. */ +# define mbspbrk rpl_mbspbrk /* avoid collision with HP-UX function */ +extern char * mbspbrk (const char *string, const char *accept); +#endif + +#if @GNULIB_MBSSPN@ +/* Find the first occurrence in the character string STRING of any character + not in the character string REJECT. Return the number of bytes from the + beginning of the string to this occurrence, or to the end of the string + if none exists. + Unlike strspn(), this function works correctly in multibyte locales. */ +extern size_t mbsspn (const char *string, const char *reject); +#endif + +#if @GNULIB_MBSSEP@ +/* Search the next delimiter (multibyte character listed in the character + string DELIM) starting at the character string *STRINGP. + If one is found, overwrite it with a NUL, and advance *STRINGP to point + to the next multibyte character after it. Otherwise, set *STRINGP to NULL. + If *STRINGP was already NULL, nothing happens. + Return the old value of *STRINGP. + + This is a variant of mbstok_r() that supports empty fields. + + Caveat: It modifies the original string. + Caveat: These functions cannot be used on constant strings. + Caveat: The identity of the delimiting character is lost. + + See also mbstok_r(). */ +extern char * mbssep (char **stringp, const char *delim); +#endif + +#if @GNULIB_MBSTOK_R@ +/* Parse the character string STRING into tokens separated by characters in + the character string DELIM. + If STRING is NULL, the saved pointer in SAVE_PTR is used as + the next starting point. For example: + char s[] = "-abc-=-def"; + char *sp; + x = mbstok_r(s, "-", &sp); // x = "abc", sp = "=-def" + x = mbstok_r(NULL, "-=", &sp); // x = "def", sp = NULL + x = mbstok_r(NULL, "=", &sp); // x = NULL + // s = "abc\0-def\0" + + Caveat: It modifies the original string. + Caveat: These functions cannot be used on constant strings. + Caveat: The identity of the delimiting character is lost. + + See also mbssep(). */ +extern char * mbstok_r (char *string, const char *delim, char **save_ptr); +#endif + +/* Map any int, typically from errno, into an error message. */ +#if @GNULIB_STRERROR@ +# if @REPLACE_STRERROR@ +# undef strerror +# define strerror rpl_strerror +extern char *strerror (int); +# endif +#elif defined GNULIB_POSIXCHECK +# undef strerror +# define strerror(e) \ + (GL_LINK_WARNING ("strerror is unportable - " \ + "use gnulib module strerror to guarantee non-NULL result"), \ + strerror (e)) +#endif + + +#ifdef __cplusplus +} +#endif + +#endif /* _GL_STRING_H */ +#endif /* _GL_STRING_H */ diff --git a/src/bin/findutils/gnulib/lib/stripslash.c b/src/bin/findutils/gnulib/lib/stripslash.c new file mode 100644 index 0000000000..40844102ff --- /dev/null +++ b/src/bin/findutils/gnulib/lib/stripslash.c @@ -0,0 +1,44 @@ +/* stripslash.c -- remove redundant trailing slashes from a file name + + Copyright (C) 1990, 2001, 2003-2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "dirname.h" + +/* Remove trailing slashes from FILE. Return true if a trailing slash + was removed. This is useful when using file name completion from a + shell that adds a "/" after directory names (such as tcsh and + bash), because on symlinks to directories, several system calls + have different semantics according to whether a trailing slash is + present. */ + +bool +strip_trailing_slashes (char *file) +{ + char *base = last_component (file); + char *base_lim; + bool had_slash; + + /* last_component returns "" for file system roots, but we need to turn + `///' into `/'. */ + if (! *base) + base = file; + base_lim = base + base_len (base); + had_slash = (*base_lim != '\0'); + *base_lim = '\0'; + return had_slash; +} diff --git a/src/bin/findutils/gnulib/lib/strndup.c b/src/bin/findutils/gnulib/lib/strndup.c new file mode 100644 index 0000000000..507e9c06a6 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/strndup.c @@ -0,0 +1,37 @@ +/* A replacement function, for systems that lack strndup. + + Copyright (C) 1996, 1997, 1998, 2001, 2002, 2003, 2005, 2006, 2007 + Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation; either version 3, or (at your option) any + later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#include + +#include + +#include + +char * +strndup (char const *s, size_t n) +{ + size_t len = strnlen (s, n); + char *new = malloc (len + 1); + + if (new == NULL) + return NULL; + + new[len] = '\0'; + return memcpy (new, s, len); +} diff --git a/src/bin/findutils/gnulib/lib/strnlen.c b/src/bin/findutils/gnulib/lib/strnlen.c new file mode 100644 index 0000000000..93d1ac149b --- /dev/null +++ b/src/bin/findutils/gnulib/lib/strnlen.c @@ -0,0 +1,31 @@ +/* Find the length of STRING, but scan at most MAXLEN characters. + Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc. + Written by Simon Josefsson. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#include + +#include + +/* Find the length of STRING, but scan at most MAXLEN characters. + If no '\0' terminator is found in that many characters, return MAXLEN. */ + +size_t +strnlen (const char *string, size_t maxlen) +{ + const char *end = memchr (string, '\0', maxlen); + return end ? (size_t) (end - string) : maxlen; +} diff --git a/src/bin/findutils/gnulib/lib/strtoimax.c b/src/bin/findutils/gnulib/lib/strtoimax.c new file mode 100644 index 0000000000..ab9bcff3c7 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/strtoimax.c @@ -0,0 +1,75 @@ +/* Convert string representation of a number into an intmax_t value. + + Copyright (C) 1999, 2001, 2002, 2003, 2004, 2006 Free Software + Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert. */ + +#include + +/* Verify interface. */ +#include + +#include + +#include "verify.h" + +#ifdef UNSIGNED +# ifndef HAVE_DECL_STRTOULL +"this configure-time declaration test was not run" +# endif +# if !HAVE_DECL_STRTOULL && HAVE_UNSIGNED_LONG_LONG_INT +unsigned long long int strtoull (char const *, char **, int); +# endif + +#else + +# ifndef HAVE_DECL_STRTOLL +"this configure-time declaration test was not run" +# endif +# if !HAVE_DECL_STRTOLL && HAVE_LONG_LONG_INT +long long int strtoll (char const *, char **, int); +# endif +#endif + +#ifdef UNSIGNED +# define Have_long_long HAVE_UNSIGNED_LONG_LONG_INT +# define Int uintmax_t +# define Unsigned unsigned +# define strtoimax strtoumax +# define strtol strtoul +# define strtoll strtoull +#else +# define Have_long_long HAVE_LONG_LONG_INT +# define Int intmax_t +# define Unsigned +#endif + +Int +strtoimax (char const *ptr, char **endptr, int base) +{ +#if Have_long_long + verify (sizeof (Int) == sizeof (Unsigned long int) + || sizeof (Int) == sizeof (Unsigned long long int)); + + if (sizeof (Int) != sizeof (Unsigned long int)) + return strtoll (ptr, endptr, base); +#else + verify (sizeof (Int) == sizeof (Unsigned long int)); +#endif + + return strtol (ptr, endptr, base); +} diff --git a/src/bin/findutils/gnulib/lib/strtol.c b/src/bin/findutils/gnulib/lib/strtol.c new file mode 100644 index 0000000000..0b2c82a01c --- /dev/null +++ b/src/bin/findutils/gnulib/lib/strtol.c @@ -0,0 +1,435 @@ +/* Convert string representation of a number into an integer value. + + Copyright (C) 1991, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2003, 2005, + 2006, 2007 + Free Software Foundation, Inc. + + NOTE: The canonical source of this file is maintained with the GNU C + Library. Bugs can be reported to bug-glibc@gnu.org. + + This program is free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation; either version 3 of the License, or any + later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifdef _LIBC +# define USE_NUMBER_GROUPING +#else +# include +#endif + +#include +#include +#ifndef __set_errno +# define __set_errno(Val) errno = (Val) +#endif + +#include +#include +#include +#include + +#ifdef USE_NUMBER_GROUPING +# include "../locale/localeinfo.h" +#endif + +/* Nonzero if we are defining `strtoul' or `strtoull', operating on + unsigned integers. */ +#ifndef UNSIGNED +# define UNSIGNED 0 +# define INT LONG int +#else +# define INT unsigned LONG int +#endif + +/* Determine the name. */ +#ifdef USE_IN_EXTENDED_LOCALE_MODEL +# if UNSIGNED +# ifdef USE_WIDE_CHAR +# ifdef QUAD +# define strtol __wcstoull_l +# else +# define strtol __wcstoul_l +# endif +# else +# ifdef QUAD +# define strtol __strtoull_l +# else +# define strtol __strtoul_l +# endif +# endif +# else +# ifdef USE_WIDE_CHAR +# ifdef QUAD +# define strtol __wcstoll_l +# else +# define strtol __wcstol_l +# endif +# else +# ifdef QUAD +# define strtol __strtoll_l +# else +# define strtol __strtol_l +# endif +# endif +# endif +#else +# if UNSIGNED +# ifdef USE_WIDE_CHAR +# ifdef QUAD +# define strtol wcstoull +# else +# define strtol wcstoul +# endif +# else +# ifdef QUAD +# define strtol strtoull +# else +# define strtol strtoul +# endif +# endif +# else +# ifdef USE_WIDE_CHAR +# ifdef QUAD +# define strtol wcstoll +# else +# define strtol wcstol +# endif +# else +# ifdef QUAD +# define strtol strtoll +# endif +# endif +# endif +#endif + +/* If QUAD is defined, we are defining `strtoll' or `strtoull', + operating on `long long int's. */ +#ifdef QUAD +# define LONG long long +# define STRTOL_LONG_MIN LONG_LONG_MIN +# define STRTOL_LONG_MAX LONG_LONG_MAX +# define STRTOL_ULONG_MAX ULONG_LONG_MAX + +/* The extra casts in the following macros work around compiler bugs, + e.g., in Cray C 5.0.3.0. */ + +/* True if negative values of the signed integer type T use two's + complement, ones' complement, or signed magnitude representation, + respectively. Much GNU code assumes two's complement, but some + people like to be portable to all possible C hosts. */ +# define TYPE_TWOS_COMPLEMENT(t) ((t) ~ (t) 0 == (t) -1) +# define TYPE_ONES_COMPLEMENT(t) ((t) ~ (t) 0 == 0) +# define TYPE_SIGNED_MAGNITUDE(t) ((t) ~ (t) 0 < (t) -1) + +/* True if the arithmetic type T is signed. */ +# define TYPE_SIGNED(t) (! ((t) 0 < (t) -1)) + +/* The maximum and minimum values for the integer type T. These + macros have undefined behavior if T is signed and has padding bits. + If this is a problem for you, please let us know how to fix it for + your host. */ +# define TYPE_MINIMUM(t) \ + ((t) (! TYPE_SIGNED (t) \ + ? (t) 0 \ + : TYPE_SIGNED_MAGNITUDE (t) \ + ? ~ (t) 0 \ + : ~ (t) 0 << (sizeof (t) * CHAR_BIT - 1))) +# define TYPE_MAXIMUM(t) \ + ((t) (! TYPE_SIGNED (t) \ + ? (t) -1 \ + : ~ (~ (t) 0 << (sizeof (t) * CHAR_BIT - 1)))) + +# ifndef ULONG_LONG_MAX +# define ULONG_LONG_MAX TYPE_MAXIMUM (unsigned long long) +# endif +# ifndef LONG_LONG_MAX +# define LONG_LONG_MAX TYPE_MAXIMUM (long long int) +# endif +# ifndef LONG_LONG_MIN +# define LONG_LONG_MIN TYPE_MINIMUM (long long int) +# endif + +# if __GNUC__ == 2 && __GNUC_MINOR__ < 7 + /* Work around gcc bug with using this constant. */ + static const unsigned long long int maxquad = ULONG_LONG_MAX; +# undef STRTOL_ULONG_MAX +# define STRTOL_ULONG_MAX maxquad +# endif +#else +# define LONG long +# define STRTOL_LONG_MIN LONG_MIN +# define STRTOL_LONG_MAX LONG_MAX +# define STRTOL_ULONG_MAX ULONG_MAX +#endif + + +/* We use this code also for the extended locale handling where the + function gets as an additional argument the locale which has to be + used. To access the values we have to redefine the _NL_CURRENT + macro. */ +#ifdef USE_IN_EXTENDED_LOCALE_MODEL +# undef _NL_CURRENT +# define _NL_CURRENT(category, item) \ + (current->values[_NL_ITEM_INDEX (item)].string) +# define LOCALE_PARAM , loc +# define LOCALE_PARAM_PROTO , __locale_t loc +#else +# define LOCALE_PARAM +# define LOCALE_PARAM_PROTO +#endif + +#include + +#ifdef USE_WIDE_CHAR +# include +# define L_(Ch) L##Ch +# define UCHAR_TYPE wint_t +# define STRING_TYPE wchar_t +# ifdef USE_IN_EXTENDED_LOCALE_MODEL +# define ISSPACE(Ch) __iswspace_l ((Ch), loc) +# define ISALPHA(Ch) __iswalpha_l ((Ch), loc) +# define TOUPPER(Ch) __towupper_l ((Ch), loc) +# else +# define ISSPACE(Ch) iswspace (Ch) +# define ISALPHA(Ch) iswalpha (Ch) +# define TOUPPER(Ch) towupper (Ch) +# endif +#else +# define L_(Ch) Ch +# define UCHAR_TYPE unsigned char +# define STRING_TYPE char +# ifdef USE_IN_EXTENDED_LOCALE_MODEL +# define ISSPACE(Ch) __isspace_l ((Ch), loc) +# define ISALPHA(Ch) __isalpha_l ((Ch), loc) +# define TOUPPER(Ch) __toupper_l ((Ch), loc) +# else +# define ISSPACE(Ch) isspace (Ch) +# define ISALPHA(Ch) isalpha (Ch) +# define TOUPPER(Ch) toupper (Ch) +# endif +#endif + +#define INTERNAL(X) INTERNAL1(X) +#define INTERNAL1(X) __##X##_internal +#define WEAKNAME(X) WEAKNAME1(X) + +#ifdef USE_NUMBER_GROUPING +/* This file defines a function to check for correct grouping. */ +# include "grouping.h" +#endif + + + +/* Convert NPTR to an `unsigned long int' or `long int' in base BASE. + If BASE is 0 the base is determined by the presence of a leading + zero, indicating octal or a leading "0x" or "0X", indicating hexadecimal. + If BASE is < 2 or > 36, it is reset to 10. + If ENDPTR is not NULL, a pointer to the character after the last + one converted is stored in *ENDPTR. */ + +INT +INTERNAL (strtol) (const STRING_TYPE *nptr, STRING_TYPE **endptr, + int base, int group LOCALE_PARAM_PROTO) +{ + int negative; + register unsigned LONG int cutoff; + register unsigned int cutlim; + register unsigned LONG int i; + register const STRING_TYPE *s; + register UCHAR_TYPE c; + const STRING_TYPE *save, *end; + int overflow; + +#ifdef USE_NUMBER_GROUPING +# ifdef USE_IN_EXTENDED_LOCALE_MODEL + struct locale_data *current = loc->__locales[LC_NUMERIC]; +# endif + /* The thousands character of the current locale. */ + wchar_t thousands = L'\0'; + /* The numeric grouping specification of the current locale, + in the format described in . */ + const char *grouping; + + if (group) + { + grouping = _NL_CURRENT (LC_NUMERIC, GROUPING); + if (*grouping <= 0 || *grouping == CHAR_MAX) + grouping = NULL; + else + { + /* Figure out the thousands separator character. */ +# if defined _LIBC || defined _HAVE_BTOWC + thousands = __btowc (*_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP)); + if (thousands == WEOF) + thousands = L'\0'; +# endif + if (thousands == L'\0') + grouping = NULL; + } + } + else + grouping = NULL; +#endif + + if (base < 0 || base == 1 || base > 36) + { + __set_errno (EINVAL); + return 0; + } + + save = s = nptr; + + /* Skip white space. */ + while (ISSPACE (*s)) + ++s; + if (*s == L_('\0')) + goto noconv; + + /* Check for a sign. */ + if (*s == L_('-')) + { + negative = 1; + ++s; + } + else if (*s == L_('+')) + { + negative = 0; + ++s; + } + else + negative = 0; + + /* Recognize number prefix and if BASE is zero, figure it out ourselves. */ + if (*s == L_('0')) + { + if ((base == 0 || base == 16) && TOUPPER (s[1]) == L_('X')) + { + s += 2; + base = 16; + } + else if (base == 0) + base = 8; + } + else if (base == 0) + base = 10; + + /* Save the pointer so we can check later if anything happened. */ + save = s; + +#ifdef USE_NUMBER_GROUPING + if (group) + { + /* Find the end of the digit string and check its grouping. */ + end = s; + for (c = *end; c != L_('\0'); c = *++end) + if ((wchar_t) c != thousands + && ((wchar_t) c < L_('0') || (wchar_t) c > L_('9')) + && (!ISALPHA (c) || (int) (TOUPPER (c) - L_('A') + 10) >= base)) + break; + if (*s == thousands) + end = s; + else + end = correctly_grouped_prefix (s, end, thousands, grouping); + } + else +#endif + end = NULL; + + cutoff = STRTOL_ULONG_MAX / (unsigned LONG int) base; + cutlim = STRTOL_ULONG_MAX % (unsigned LONG int) base; + + overflow = 0; + i = 0; + for (c = *s; c != L_('\0'); c = *++s) + { + if (s == end) + break; + if (c >= L_('0') && c <= L_('9')) + c -= L_('0'); + else if (ISALPHA (c)) + c = TOUPPER (c) - L_('A') + 10; + else + break; + if ((int) c >= base) + break; + /* Check for overflow. */ + if (i > cutoff || (i == cutoff && c > cutlim)) + overflow = 1; + else + { + i *= (unsigned LONG int) base; + i += c; + } + } + + /* Check if anything actually happened. */ + if (s == save) + goto noconv; + + /* Store in ENDPTR the address of one character + past the last character we converted. */ + if (endptr != NULL) + *endptr = (STRING_TYPE *) s; + +#if !UNSIGNED + /* Check for a value that is within the range of + `unsigned LONG int', but outside the range of `LONG int'. */ + if (overflow == 0 + && i > (negative + ? -((unsigned LONG int) (STRTOL_LONG_MIN + 1)) + 1 + : (unsigned LONG int) STRTOL_LONG_MAX)) + overflow = 1; +#endif + + if (overflow) + { + __set_errno (ERANGE); +#if UNSIGNED + return STRTOL_ULONG_MAX; +#else + return negative ? STRTOL_LONG_MIN : STRTOL_LONG_MAX; +#endif + } + + /* Return the result of the appropriate sign. */ + return negative ? -i : i; + +noconv: + /* We must handle a special case here: the base is 0 or 16 and the + first two characters are '0' and 'x', but the rest are no + hexadecimal digits. This is no error case. We return 0 and + ENDPTR points to the `x`. */ + if (endptr != NULL) + { + if (save - nptr >= 2 && TOUPPER (save[-1]) == L_('X') + && save[-2] == L_('0')) + *endptr = (STRING_TYPE *) &save[-1]; + else + /* There was no number to convert. */ + *endptr = (STRING_TYPE *) nptr; + } + + return 0L; +} + +/* External user entry point. */ + + +INT +#ifdef weak_function +weak_function +#endif +strtol (const STRING_TYPE *nptr, STRING_TYPE **endptr, + int base LOCALE_PARAM_PROTO) +{ + return INTERNAL (strtol) (nptr, endptr, base, 0 LOCALE_PARAM); +} diff --git a/src/bin/findutils/gnulib/lib/strtoll.c b/src/bin/findutils/gnulib/lib/strtoll.c new file mode 100644 index 0000000000..ccc99cb43c --- /dev/null +++ b/src/bin/findutils/gnulib/lib/strtoll.c @@ -0,0 +1,32 @@ +/* Function to parse a `long long int' from text. + Copyright (C) 1995, 1996, 1997, 1999, 2001 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#define QUAD 1 + +#include + +#ifdef _LIBC +# ifdef SHARED +# include + +# if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_2) +compat_symbol (libc, __strtoll_internal, __strtoq_internal, GLIBC_2_0); +# endif + +# endif +weak_alias (strtoll, strtoq) +#endif diff --git a/src/bin/findutils/gnulib/lib/strtoul.c b/src/bin/findutils/gnulib/lib/strtoul.c new file mode 100644 index 0000000000..88dbfc0741 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/strtoul.c @@ -0,0 +1,19 @@ +/* Copyright (C) 1991, 1997 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#define UNSIGNED 1 + +#include "strtol.c" diff --git a/src/bin/findutils/gnulib/lib/strtoull.c b/src/bin/findutils/gnulib/lib/strtoull.c new file mode 100644 index 0000000000..eda4a70697 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/strtoull.c @@ -0,0 +1,26 @@ +/* Function to parse an `unsigned long long int' from text. + Copyright (C) 1995, 1996, 1997, 1999 Free Software Foundation, Inc. + NOTE: The canonical source of this file is maintained with the GNU C + Library. Bugs can be reported to bug-glibc@gnu.org. + + This program is free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation; either version 3 of the License, or any + later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#define QUAD 1 + +#include "strtoul.c" + +#ifdef _LIBC +strong_alias (__strtoull_internal, __strtouq_internal) +weak_alias (strtoull, strtouq) +#endif diff --git a/src/bin/findutils/gnulib/lib/strtoumax.c b/src/bin/findutils/gnulib/lib/strtoumax.c new file mode 100644 index 0000000000..dc395d626a --- /dev/null +++ b/src/bin/findutils/gnulib/lib/strtoumax.c @@ -0,0 +1,2 @@ +#define UNSIGNED 1 +#include "strtoimax.c" diff --git a/src/bin/findutils/gnulib/lib/sys/stat.h b/src/bin/findutils/gnulib/lib/sys/stat.h new file mode 100644 index 0000000000..d974cd907c --- /dev/null +++ b/src/bin/findutils/gnulib/lib/sys/stat.h @@ -0,0 +1,280 @@ +/* Provide a more complete sys/stat header file. + Copyright (C) 2006, 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* Written by Eric Blake, Paul Eggert, and Jim Meyering. */ + +/* This file is supposed to be used on platforms where is + incomplete. It is intended to provide definitions and prototypes + needed by an application. Start with what the system provides. */ + +#ifndef _GL_SYS_STAT_H + +/* The include_next requires a split double-inclusion guard. */ +#include_next + +#ifndef _GL_SYS_STAT_H +#define _GL_SYS_STAT_H + +#ifndef S_IFMT +# define S_IFMT 0170000 +#endif + +#if STAT_MACROS_BROKEN +# undef S_ISBLK +# undef S_ISCHR +# undef S_ISDIR +# undef S_ISFIFO +# undef S_ISLNK +# undef S_ISNAM +# undef S_ISMPB +# undef S_ISMPC +# undef S_ISNWK +# undef S_ISREG +# undef S_ISSOCK +#endif + +#ifndef S_ISBLK +# ifdef S_IFBLK +# define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK) +# else +# define S_ISBLK(m) 0 +# endif +#endif + +#ifndef S_ISCHR +# ifdef S_IFCHR +# define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR) +# else +# define S_ISCHR(m) 0 +# endif +#endif + +#ifndef S_ISDIR +# ifdef S_IFDIR +# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) +# else +# define S_ISDIR(m) 0 +# endif +#endif + +#ifndef S_ISDOOR /* Solaris 2.5 and up */ +# define S_ISDOOR(m) 0 +#endif + +#ifndef S_ISFIFO +# ifdef S_IFIFO +# define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO) +# else +# define S_ISFIFO(m) 0 +# endif +#endif + +#ifndef S_ISLNK +# ifdef S_IFLNK +# define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK) +# else +# define S_ISLNK(m) 0 +# endif +#endif + +#ifndef S_ISMPB /* V7 */ +# ifdef S_IFMPB +# define S_ISMPB(m) (((m) & S_IFMT) == S_IFMPB) +# define S_ISMPC(m) (((m) & S_IFMT) == S_IFMPC) +# else +# define S_ISMPB(m) 0 +# define S_ISMPC(m) 0 +# endif +#endif + +#ifndef S_ISNAM /* Xenix */ +# ifdef S_IFNAM +# define S_ISNAM(m) (((m) & S_IFMT) == S_IFNAM) +# else +# define S_ISNAM(m) 0 +# endif +#endif + +#ifndef S_ISNWK /* HP/UX */ +# ifdef S_IFNWK +# define S_ISNWK(m) (((m) & S_IFMT) == S_IFNWK) +# else +# define S_ISNWK(m) 0 +# endif +#endif + +#ifndef S_ISPORT /* Solaris 10 and up */ +# define S_ISPORT(m) 0 +#endif + +#ifndef S_ISREG +# ifdef S_IFREG +# define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) +# else +# define S_ISREG(m) 0 +# endif +#endif + +#ifndef S_ISSOCK +# ifdef S_IFSOCK +# define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK) +# else +# define S_ISSOCK(m) 0 +# endif +#endif + + +#ifndef S_TYPEISMQ +# define S_TYPEISMQ(p) 0 +#endif + +#ifndef S_TYPEISTMO +# define S_TYPEISTMO(p) 0 +#endif + + +#ifndef S_TYPEISSEM +# ifdef S_INSEM +# define S_TYPEISSEM(p) (S_ISNAM ((p)->st_mode) && (p)->st_rdev == S_INSEM) +# else +# define S_TYPEISSEM(p) 0 +# endif +#endif + +#ifndef S_TYPEISSHM +# ifdef S_INSHD +# define S_TYPEISSHM(p) (S_ISNAM ((p)->st_mode) && (p)->st_rdev == S_INSHD) +# else +# define S_TYPEISSHM(p) 0 +# endif +#endif + +/* high performance ("contiguous data") */ +#ifndef S_ISCTG +# define S_ISCTG(p) 0 +#endif + +/* Cray DMF (data migration facility): off line, with data */ +#ifndef S_ISOFD +# define S_ISOFD(p) 0 +#endif + +/* Cray DMF (data migration facility): off line, with no data */ +#ifndef S_ISOFL +# define S_ISOFL(p) 0 +#endif + +/* 4.4BSD whiteout */ +#ifndef S_ISWHT +# define S_ISWHT(m) 0 +#endif + +/* If any of the following are undefined, + define them to their de facto standard values. */ +#if !S_ISUID +# define S_ISUID 04000 +#endif +#if !S_ISGID +# define S_ISGID 02000 +#endif + +/* S_ISVTX is a common extension to POSIX. */ +#ifndef S_ISVTX +# define S_ISVTX 01000 +#endif + +#if !S_IRUSR && S_IREAD +# define S_IRUSR S_IREAD +#endif +#if !S_IRUSR +# define S_IRUSR 00400 +#endif +#if !S_IRGRP +# define S_IRGRP (S_IRUSR >> 3) +#endif +#if !S_IROTH +# define S_IROTH (S_IRUSR >> 6) +#endif + +#if !S_IWUSR && S_IWRITE +# define S_IWUSR S_IWRITE +#endif +#if !S_IWUSR +# define S_IWUSR 00200 +#endif +#if !S_IWGRP +# define S_IWGRP (S_IWUSR >> 3) +#endif +#if !S_IWOTH +# define S_IWOTH (S_IWUSR >> 6) +#endif + +#if !S_IXUSR && S_IEXEC +# define S_IXUSR S_IEXEC +#endif +#if !S_IXUSR +# define S_IXUSR 00100 +#endif +#if !S_IXGRP +# define S_IXGRP (S_IXUSR >> 3) +#endif +#if !S_IXOTH +# define S_IXOTH (S_IXUSR >> 6) +#endif + +#if !S_IRWXU +# define S_IRWXU (S_IRUSR | S_IWUSR | S_IXUSR) +#endif +#if !S_IRWXG +# define S_IRWXG (S_IRGRP | S_IWGRP | S_IXGRP) +#endif +#if !S_IRWXO +# define S_IRWXO (S_IROTH | S_IWOTH | S_IXOTH) +#endif + +/* S_IXUGO is a common extension to POSIX. */ +#if !S_IXUGO +# define S_IXUGO (S_IXUSR | S_IXGRP | S_IXOTH) +#endif + +#ifndef S_IRWXUGO +# define S_IRWXUGO (S_IRWXU | S_IRWXG | S_IRWXO) +#endif + +/* mingw does not support symlinks, therefore it does not have lstat. But + without links, stat does just fine. */ +#if ! HAVE_LSTAT +# define lstat stat +#endif + +/* mingw's _mkdir() function has 1 argument, but we pass 2 arguments. + Additionally, it declares _mkdir (and depending on compile flags, an + alias mkdir), only in the nonstandard io.h. */ +#if ! HAVE_DECL_MKDIR && HAVE_IO_H +# include + +static inline int +rpl_mkdir (char const *name, mode_t mode) +{ + return _mkdir (name); +} + +# define mkdir rpl_mkdir +#endif + +#endif /* _GL_SYS_STAT_H */ +#endif /* _GL_SYS_STAT_H */ diff --git a/src/bin/findutils/gnulib/lib/sys_stat.in.h b/src/bin/findutils/gnulib/lib/sys_stat.in.h new file mode 100644 index 0000000000..b60e32298c --- /dev/null +++ b/src/bin/findutils/gnulib/lib/sys_stat.in.h @@ -0,0 +1,280 @@ +/* Provide a more complete sys/stat header file. + Copyright (C) 2006, 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* Written by Eric Blake, Paul Eggert, and Jim Meyering. */ + +/* This file is supposed to be used on platforms where is + incomplete. It is intended to provide definitions and prototypes + needed by an application. Start with what the system provides. */ + +#ifndef _GL_SYS_STAT_H + +/* The include_next requires a split double-inclusion guard. */ +#@INCLUDE_NEXT@ @NEXT_SYS_STAT_H@ + +#ifndef _GL_SYS_STAT_H +#define _GL_SYS_STAT_H + +#ifndef S_IFMT +# define S_IFMT 0170000 +#endif + +#if STAT_MACROS_BROKEN +# undef S_ISBLK +# undef S_ISCHR +# undef S_ISDIR +# undef S_ISFIFO +# undef S_ISLNK +# undef S_ISNAM +# undef S_ISMPB +# undef S_ISMPC +# undef S_ISNWK +# undef S_ISREG +# undef S_ISSOCK +#endif + +#ifndef S_ISBLK +# ifdef S_IFBLK +# define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK) +# else +# define S_ISBLK(m) 0 +# endif +#endif + +#ifndef S_ISCHR +# ifdef S_IFCHR +# define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR) +# else +# define S_ISCHR(m) 0 +# endif +#endif + +#ifndef S_ISDIR +# ifdef S_IFDIR +# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) +# else +# define S_ISDIR(m) 0 +# endif +#endif + +#ifndef S_ISDOOR /* Solaris 2.5 and up */ +# define S_ISDOOR(m) 0 +#endif + +#ifndef S_ISFIFO +# ifdef S_IFIFO +# define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO) +# else +# define S_ISFIFO(m) 0 +# endif +#endif + +#ifndef S_ISLNK +# ifdef S_IFLNK +# define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK) +# else +# define S_ISLNK(m) 0 +# endif +#endif + +#ifndef S_ISMPB /* V7 */ +# ifdef S_IFMPB +# define S_ISMPB(m) (((m) & S_IFMT) == S_IFMPB) +# define S_ISMPC(m) (((m) & S_IFMT) == S_IFMPC) +# else +# define S_ISMPB(m) 0 +# define S_ISMPC(m) 0 +# endif +#endif + +#ifndef S_ISNAM /* Xenix */ +# ifdef S_IFNAM +# define S_ISNAM(m) (((m) & S_IFMT) == S_IFNAM) +# else +# define S_ISNAM(m) 0 +# endif +#endif + +#ifndef S_ISNWK /* HP/UX */ +# ifdef S_IFNWK +# define S_ISNWK(m) (((m) & S_IFMT) == S_IFNWK) +# else +# define S_ISNWK(m) 0 +# endif +#endif + +#ifndef S_ISPORT /* Solaris 10 and up */ +# define S_ISPORT(m) 0 +#endif + +#ifndef S_ISREG +# ifdef S_IFREG +# define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) +# else +# define S_ISREG(m) 0 +# endif +#endif + +#ifndef S_ISSOCK +# ifdef S_IFSOCK +# define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK) +# else +# define S_ISSOCK(m) 0 +# endif +#endif + + +#ifndef S_TYPEISMQ +# define S_TYPEISMQ(p) 0 +#endif + +#ifndef S_TYPEISTMO +# define S_TYPEISTMO(p) 0 +#endif + + +#ifndef S_TYPEISSEM +# ifdef S_INSEM +# define S_TYPEISSEM(p) (S_ISNAM ((p)->st_mode) && (p)->st_rdev == S_INSEM) +# else +# define S_TYPEISSEM(p) 0 +# endif +#endif + +#ifndef S_TYPEISSHM +# ifdef S_INSHD +# define S_TYPEISSHM(p) (S_ISNAM ((p)->st_mode) && (p)->st_rdev == S_INSHD) +# else +# define S_TYPEISSHM(p) 0 +# endif +#endif + +/* high performance ("contiguous data") */ +#ifndef S_ISCTG +# define S_ISCTG(p) 0 +#endif + +/* Cray DMF (data migration facility): off line, with data */ +#ifndef S_ISOFD +# define S_ISOFD(p) 0 +#endif + +/* Cray DMF (data migration facility): off line, with no data */ +#ifndef S_ISOFL +# define S_ISOFL(p) 0 +#endif + +/* 4.4BSD whiteout */ +#ifndef S_ISWHT +# define S_ISWHT(m) 0 +#endif + +/* If any of the following are undefined, + define them to their de facto standard values. */ +#if !S_ISUID +# define S_ISUID 04000 +#endif +#if !S_ISGID +# define S_ISGID 02000 +#endif + +/* S_ISVTX is a common extension to POSIX. */ +#ifndef S_ISVTX +# define S_ISVTX 01000 +#endif + +#if !S_IRUSR && S_IREAD +# define S_IRUSR S_IREAD +#endif +#if !S_IRUSR +# define S_IRUSR 00400 +#endif +#if !S_IRGRP +# define S_IRGRP (S_IRUSR >> 3) +#endif +#if !S_IROTH +# define S_IROTH (S_IRUSR >> 6) +#endif + +#if !S_IWUSR && S_IWRITE +# define S_IWUSR S_IWRITE +#endif +#if !S_IWUSR +# define S_IWUSR 00200 +#endif +#if !S_IWGRP +# define S_IWGRP (S_IWUSR >> 3) +#endif +#if !S_IWOTH +# define S_IWOTH (S_IWUSR >> 6) +#endif + +#if !S_IXUSR && S_IEXEC +# define S_IXUSR S_IEXEC +#endif +#if !S_IXUSR +# define S_IXUSR 00100 +#endif +#if !S_IXGRP +# define S_IXGRP (S_IXUSR >> 3) +#endif +#if !S_IXOTH +# define S_IXOTH (S_IXUSR >> 6) +#endif + +#if !S_IRWXU +# define S_IRWXU (S_IRUSR | S_IWUSR | S_IXUSR) +#endif +#if !S_IRWXG +# define S_IRWXG (S_IRGRP | S_IWGRP | S_IXGRP) +#endif +#if !S_IRWXO +# define S_IRWXO (S_IROTH | S_IWOTH | S_IXOTH) +#endif + +/* S_IXUGO is a common extension to POSIX. */ +#if !S_IXUGO +# define S_IXUGO (S_IXUSR | S_IXGRP | S_IXOTH) +#endif + +#ifndef S_IRWXUGO +# define S_IRWXUGO (S_IRWXU | S_IRWXG | S_IRWXO) +#endif + +/* mingw does not support symlinks, therefore it does not have lstat. But + without links, stat does just fine. */ +#if ! @HAVE_LSTAT@ +# define lstat stat +#endif + +/* mingw's _mkdir() function has 1 argument, but we pass 2 arguments. + Additionally, it declares _mkdir (and depending on compile flags, an + alias mkdir), only in the nonstandard io.h. */ +#if ! @HAVE_DECL_MKDIR@ && @HAVE_IO_H@ +# include + +static inline int +rpl_mkdir (char const *name, mode_t mode) +{ + return _mkdir (name); +} + +# define mkdir rpl_mkdir +#endif + +#endif /* _GL_SYS_STAT_H */ +#endif /* _GL_SYS_STAT_H */ diff --git a/src/bin/findutils/gnulib/lib/time.h b/src/bin/findutils/gnulib/lib/time.h new file mode 100644 index 0000000000..2403c68ecb --- /dev/null +++ b/src/bin/findutils/gnulib/lib/time.h @@ -0,0 +1,115 @@ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +/* A more-standard . + + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* Don't get in the way of glibc when it includes time.h merely to + declare a few standard symbols, rather than to declare all the + symbols. Also, Solaris 8 eventually includes itself + recursively; if that is happening, just include the system + without adding our own declarations. */ +#if (defined __need_time_t || defined __need_clock_t \ + || defined __need_timespec \ + || defined _GL_TIME_H) + +# include_next + +#else + +# define _GL_TIME_H + +# include_next + +# ifdef __cplusplus +extern "C" { +# endif + +/* Some systems don't define struct timespec (e.g., AIX 4.1, Ultrix 4.3). + Or they define it with the wrong member names or define it in + (e.g., FreeBSD circa 1997). */ +# if ! 1 +# if 0 +# include +# else +# undef timespec +# define timespec rpl_timespec +struct timespec +{ + time_t tv_sec; + long int tv_nsec; +}; +# endif +# endif + +/* Sleep for at least RQTP seconds unless interrupted, If interrupted, + return -1 and store the remaining time into RMTP. See + . */ +# if GNULIB_PORTCHECK +# define nanosleep rpl_nanosleep +int nanosleep (struct timespec const *__rqtp, struct timespec *__rmtp); +# endif + +/* Convert TIMER to RESULT, assuming local time and UTC respectively. See + and + . */ +# if 0 +# undef localtime_r +# define localtime_r rpl_localtime_r +# undef gmtime_r +# define gmtime_r rpl_gmtime_r +struct tm *localtime_r (time_t const *restrict __timer, + struct tm *restrict __result); +struct tm *gmtime_r (time_t const *restrict __timer, + struct tm *restrict __result); +# endif + +/* Parse BUF as a time stamp, assuming FORMAT specifies its layout, and store + the resulting broken-down time into TM. See + . */ +# if GNULIB_PORTCHECK +# undef strptime +# define strptime rpl_strptime +char *strptime (char const *restrict __buf, char const *restrict __format, + struct tm *restrict __tm); +# endif + +/* Convert TM to a time_t value, assuming UTC. */ +# if GNULIB_PORTCHECK +# undef timegm +# define timegm rpl_timegm +time_t timegm (struct tm *__tm); +# endif + +/* Encourage applications to avoid unsafe functions that can overrun + buffers when given outlandish struct tm values. Portable + applications should use strftime (or even sprintf) instead. */ +# if GNULIB_PORTCHECK +# undef asctime +# define asctime eschew_asctime +# undef asctime_r +# define asctime_r eschew_asctime_r +# undef ctime +# define ctime eschew_ctime +# undef ctime_r +# define ctime_r eschew_ctime_r +# endif + +# ifdef __cplusplus +} +# endif + +#endif diff --git a/src/bin/findutils/gnulib/lib/time.in.h b/src/bin/findutils/gnulib/lib/time.in.h new file mode 100644 index 0000000000..71c2b30b1f --- /dev/null +++ b/src/bin/findutils/gnulib/lib/time.in.h @@ -0,0 +1,114 @@ +/* A more-standard . + + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* Don't get in the way of glibc when it includes time.h merely to + declare a few standard symbols, rather than to declare all the + symbols. Also, Solaris 8 eventually includes itself + recursively; if that is happening, just include the system + without adding our own declarations. */ +#if (defined __need_time_t || defined __need_clock_t \ + || defined __need_timespec \ + || defined _GL_TIME_H) + +# @INCLUDE_NEXT@ @NEXT_TIME_H@ + +#else + +# define _GL_TIME_H + +# @INCLUDE_NEXT@ @NEXT_TIME_H@ + +# ifdef __cplusplus +extern "C" { +# endif + +/* Some systems don't define struct timespec (e.g., AIX 4.1, Ultrix 4.3). + Or they define it with the wrong member names or define it in + (e.g., FreeBSD circa 1997). */ +# if ! @TIME_H_DEFINES_STRUCT_TIMESPEC@ +# if @SYS_TIME_H_DEFINES_STRUCT_TIMESPEC@ +# include +# else +# undef timespec +# define timespec rpl_timespec +struct timespec +{ + time_t tv_sec; + long int tv_nsec; +}; +# endif +# endif + +/* Sleep for at least RQTP seconds unless interrupted, If interrupted, + return -1 and store the remaining time into RMTP. See + . */ +# if @REPLACE_NANOSLEEP@ +# define nanosleep rpl_nanosleep +int nanosleep (struct timespec const *__rqtp, struct timespec *__rmtp); +# endif + +/* Convert TIMER to RESULT, assuming local time and UTC respectively. See + and + . */ +# if @REPLACE_LOCALTIME_R@ +# undef localtime_r +# define localtime_r rpl_localtime_r +# undef gmtime_r +# define gmtime_r rpl_gmtime_r +struct tm *localtime_r (time_t const *restrict __timer, + struct tm *restrict __result); +struct tm *gmtime_r (time_t const *restrict __timer, + struct tm *restrict __result); +# endif + +/* Parse BUF as a time stamp, assuming FORMAT specifies its layout, and store + the resulting broken-down time into TM. See + . */ +# if @REPLACE_STRPTIME@ +# undef strptime +# define strptime rpl_strptime +char *strptime (char const *restrict __buf, char const *restrict __format, + struct tm *restrict __tm); +# endif + +/* Convert TM to a time_t value, assuming UTC. */ +# if @REPLACE_TIMEGM@ +# undef timegm +# define timegm rpl_timegm +time_t timegm (struct tm *__tm); +# endif + +/* Encourage applications to avoid unsafe functions that can overrun + buffers when given outlandish struct tm values. Portable + applications should use strftime (or even sprintf) instead. */ +# if GNULIB_PORTCHECK +# undef asctime +# define asctime eschew_asctime +# undef asctime_r +# define asctime_r eschew_asctime_r +# undef ctime +# define ctime eschew_ctime +# undef ctime_r +# define ctime_r eschew_ctime_r +# endif + +# ifdef __cplusplus +} +# endif + +#endif diff --git a/src/bin/findutils/gnulib/lib/time_r.c b/src/bin/findutils/gnulib/lib/time_r.c new file mode 100644 index 0000000000..d610e7fe23 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/time_r.c @@ -0,0 +1,47 @@ +/* Reentrant time functions like localtime_r. + + Copyright (C) 2003, 2006, 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* Written by Paul Eggert. */ + +#include + +#include + +#include + +static struct tm * +copy_tm_result (struct tm *dest, struct tm const *src) +{ + if (! src) + return 0; + *dest = *src; + return dest; +} + + +struct tm * +gmtime_r (time_t const * restrict t, struct tm * restrict tp) +{ + return copy_tm_result (tp, gmtime (t)); +} + +struct tm * +localtime_r (time_t const * restrict t, struct tm * restrict tp) +{ + return copy_tm_result (tp, localtime (t)); +} diff --git a/src/bin/findutils/gnulib/lib/unistd--.h b/src/bin/findutils/gnulib/lib/unistd--.h new file mode 100644 index 0000000000..1a7fd785b0 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/unistd--.h @@ -0,0 +1,27 @@ +/* Like unistd.h, but redefine some names to avoid glitches. + + Copyright (C) 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert. */ + +#include +#include "unistd-safer.h" + +#undef dup +#define dup dup_safer + +#undef pipe +#define pipe pipe_safer diff --git a/src/bin/findutils/gnulib/lib/unistd-safer.h b/src/bin/findutils/gnulib/lib/unistd-safer.h new file mode 100644 index 0000000000..033e857d7a --- /dev/null +++ b/src/bin/findutils/gnulib/lib/unistd-safer.h @@ -0,0 +1,22 @@ +/* Invoke unistd-like functions, but avoid some glitches. + + Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert. */ + +int dup_safer (int); +int fd_safer (int); +int pipe_safer (int[2]); diff --git a/src/bin/findutils/gnulib/lib/unistd.h b/src/bin/findutils/gnulib/lib/unistd.h new file mode 100644 index 0000000000..4df4d9b1d5 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/unistd.h @@ -0,0 +1,318 @@ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +/* Substitute for and wrapper around . + Copyright (C) 2004-2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _GL_UNISTD_H + +/* The include_next requires a split double-inclusion guard. */ +#if 1 +# include_next +#endif + +#ifndef _GL_UNISTD_H +#define _GL_UNISTD_H + +/* mingw doesn't define the SEEK_* macros in . */ +#if !(defined SEEK_CUR && defined SEEK_END && defined SEEK_SET) +# include +#endif + +/* mingw fails to declare _exit in . */ +#include + +/* The definition of GL_LINK_WARNING is copied here. */ + + +/* Declare overridden functions. */ + +#ifdef __cplusplus +extern "C" { +#endif + + +#if 1 +# if 1 +# ifndef REPLACE_CHOWN +# define REPLACE_CHOWN 1 +# endif +# if REPLACE_CHOWN +/* Change the owner of FILE to UID (if UID is not -1) and the group of FILE + to GID (if GID is not -1). Follow symbolic links. + Return 0 if successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +# define chown rpl_chown +extern int chown (const char *file, uid_t uid, gid_t gid); +# endif +# endif +#elif defined GNULIB_POSIXCHECK +# undef chown +# define chown(f,u,g) \ + (GL_LINK_WARNING ("chown fails to follow symlinks on some systems and " \ + "doesn't treat a uid or gid of -1 on some systems - " \ + "use gnulib module chown for portability"), \ + chown (f, u, g)) +#endif + + +#if 1 +# if !1 +/* Copy the file descriptor OLDFD into file descriptor NEWFD. Do nothing if + NEWFD = OLDFD, otherwise close NEWFD first if it is open. + Return 0 if successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +extern int dup2 (int oldfd, int newfd); +# endif +#elif defined GNULIB_POSIXCHECK +# undef dup2 +# define dup2(o,n) \ + (GL_LINK_WARNING ("dup2 is unportable - " \ + "use gnulib module dup2 for portability"), \ + dup2 (o, n)) +#endif + + +#if 1 +# if 0 + +/* Change the process' current working directory to the directory on which + the given file descriptor is open. + Return 0 if successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +extern int fchdir (int /*fd*/); + +# define close rpl_close +extern int close (int); +# define dup rpl_dup +extern int dup (int); +# define dup2 rpl_dup2 +extern int dup2 (int, int); + +# endif +#elif defined GNULIB_POSIXCHECK +# undef fchdir +# define fchdir(f) \ + (GL_LINK_WARNING ("fchdir is unportable - " \ + "use gnulib module fchdir for portability"), \ + fchdir (f)) +#endif + + +#if 0 +# if !1 +/* Change the size of the file to which FD is opened to become equal to LENGTH. + Return 0 if successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +extern int ftruncate (int fd, off_t length); +# endif +#elif defined GNULIB_POSIXCHECK +# undef ftruncate +# define ftruncate(f,l) \ + (GL_LINK_WARNING ("ftruncate is unportable - " \ + "use gnulib module ftruncate for portability"), \ + ftruncate (f, l)) +#endif + + +#if 1 +/* Include the headers that might declare getcwd so that they will not + cause confusion if included after this file. */ +# include +# if 1 +/* Get the name of the current working directory, and put it in SIZE bytes + of BUF. + Return BUF if successful, or NULL if the directory couldn't be determined + or SIZE was too small. + See the POSIX:2001 specification + . + Additionally, the gnulib module 'getcwd' guarantees the following GNU + extension: If BUF is NULL, an array is allocated with 'malloc'; the array + is SIZE bytes long, unless SIZE == 0, in which case it is as big as + necessary. */ +# define getcwd rpl_getcwd +extern char * getcwd (char *buf, size_t size); +# endif +#elif defined GNULIB_POSIXCHECK +# undef getcwd +# define getcwd(b,s) \ + (GL_LINK_WARNING ("getcwd is unportable - " \ + "use gnulib module getcwd for portability"), \ + getcwd (b, s)) +#endif + + +#if 0 +/* Copies the user's login name to NAME. + The array pointed to by NAME has room for SIZE bytes. + + Returns 0 if successful. Upon error, an error number is returned, or -1 in + the case that the login name cannot be found but no specific error is + provided (this case is hopefully rare but is left open by the POSIX spec). + + See . + */ +# if !1 +# include +extern int getlogin_r (char *name, size_t size); +# endif +#elif defined GNULIB_POSIXCHECK +# undef getlogin_r +# define getlogin_r(n,s) \ + (GL_LINK_WARNING ("getlogin_r is unportable - " \ + "use gnulib module getlogin_r for portability"), \ + getlogin_r (n, s)) +#endif + + +#if 0 +# if !1 +/* This is for POSIX systems. */ +# if !defined getpagesize && defined _SC_PAGESIZE +# if ! (defined __VMS && __VMS_VER < 70000000) +# define getpagesize() sysconf (_SC_PAGESIZE) +# endif +# endif +/* This is for older VMS. */ +# if !defined getpagesize && defined __VMS +# ifdef __ALPHA +# define getpagesize() 8192 +# else +# define getpagesize() 512 +# endif +# endif +/* This is for BeOS. */ +# if !defined getpagesize && 0 +# include +# if defined B_PAGE_SIZE +# define getpagesize() B_PAGE_SIZE +# endif +# endif +/* This is for AmigaOS4.0. */ +# if !defined getpagesize && defined __amigaos4__ +# define getpagesize() 2048 +# endif +/* This is for older Unix systems. */ +# if !defined getpagesize && 0 +# include +# ifdef EXEC_PAGESIZE +# define getpagesize() EXEC_PAGESIZE +# else +# ifdef NBPG +# ifndef CLSIZE +# define CLSIZE 1 +# endif +# define getpagesize() (NBPG * CLSIZE) +# else +# ifdef NBPC +# define getpagesize() NBPC +# endif +# endif +# endif +# endif +# endif +#elif defined GNULIB_POSIXCHECK +# undef getpagesize +# define getpagesize() \ + (GL_LINK_WARNING ("getpagesize is unportable - " \ + "use gnulib module getpagesize for portability"), \ + getpagesize ()) +#endif + + +#if 1 +# if 0 +/* Change the owner of FILE to UID (if UID is not -1) and the group of FILE + to GID (if GID is not -1). Do not follow symbolic links. + Return 0 if successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +# define lchown rpl_lchown +extern int lchown (char const *file, uid_t owner, gid_t group); +# endif +#elif defined GNULIB_POSIXCHECK +# undef lchown +# define lchown(f,u,g) \ + (GL_LINK_WARNING ("lchown is unportable to pre-POSIX.1-2001 " \ + "systems - use gnulib module lchown for portability"), \ + lchown (f, u, g)) +#endif + + +#if 1 +# if 0 +/* Set the offset of FD relative to SEEK_SET, SEEK_CUR, or SEEK_END. + Return the new offset if successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +# define lseek rpl_lseek + extern off_t lseek (int fd, off_t offset, int whence); +# endif +#elif defined GNULIB_POSIXCHECK +# undef lseek +# define lseek(f,o,w) \ + (GL_LINK_WARNING ("lseek does not fail with ESPIPE on pipes on some " \ + "systems - use gnulib module lseek for portability"), \ + lseek (f, o, w)) +#endif + + +#if 1 +/* Read the contents of the symbolic link FILE and place the first BUFSIZE + bytes of it into BUF. Return the number of bytes placed into BUF if + successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +# if !1 +# include +extern int readlink (const char *file, char *buf, size_t bufsize); +# endif +#elif defined GNULIB_POSIXCHECK +# undef readlink +# define readlink(f,b,s) \ + (GL_LINK_WARNING ("readlink is unportable - " \ + "use gnulib module readlink for portability"), \ + readlink (f, b, s)) +#endif + + +#if 0 +/* Pause the execution of the current thread for N seconds. + Returns the number of seconds left to sleep. + See the POSIX:2001 specification + . */ +# if !1 +extern unsigned int sleep (unsigned int n); +# endif +#elif defined GNULIB_POSIXCHECK +# undef sleep +# define sleep(n) \ + (GL_LINK_WARNING ("sleep is unportable - " \ + "use gnulib module sleep for portability"), \ + sleep (n)) +#endif + + +#ifdef __cplusplus +} +#endif + + +#endif /* _GL_UNISTD_H */ +#endif /* _GL_UNISTD_H */ diff --git a/src/bin/findutils/gnulib/lib/unistd.in.h b/src/bin/findutils/gnulib/lib/unistd.in.h new file mode 100644 index 0000000000..a224889591 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/unistd.in.h @@ -0,0 +1,317 @@ +/* Substitute for and wrapper around . + Copyright (C) 2004-2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#ifndef _GL_UNISTD_H + +/* The include_next requires a split double-inclusion guard. */ +#if @HAVE_UNISTD_H@ +# @INCLUDE_NEXT@ @NEXT_UNISTD_H@ +#endif + +#ifndef _GL_UNISTD_H +#define _GL_UNISTD_H + +/* mingw doesn't define the SEEK_* macros in . */ +#if !(defined SEEK_CUR && defined SEEK_END && defined SEEK_SET) +# include +#endif + +/* mingw fails to declare _exit in . */ +#include + +/* The definition of GL_LINK_WARNING is copied here. */ + + +/* Declare overridden functions. */ + +#ifdef __cplusplus +extern "C" { +#endif + + +#if @GNULIB_CHOWN@ +# if @REPLACE_CHOWN@ +# ifndef REPLACE_CHOWN +# define REPLACE_CHOWN 1 +# endif +# if REPLACE_CHOWN +/* Change the owner of FILE to UID (if UID is not -1) and the group of FILE + to GID (if GID is not -1). Follow symbolic links. + Return 0 if successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +# define chown rpl_chown +extern int chown (const char *file, uid_t uid, gid_t gid); +# endif +# endif +#elif defined GNULIB_POSIXCHECK +# undef chown +# define chown(f,u,g) \ + (GL_LINK_WARNING ("chown fails to follow symlinks on some systems and " \ + "doesn't treat a uid or gid of -1 on some systems - " \ + "use gnulib module chown for portability"), \ + chown (f, u, g)) +#endif + + +#if @GNULIB_DUP2@ +# if !@HAVE_DUP2@ +/* Copy the file descriptor OLDFD into file descriptor NEWFD. Do nothing if + NEWFD = OLDFD, otherwise close NEWFD first if it is open. + Return 0 if successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +extern int dup2 (int oldfd, int newfd); +# endif +#elif defined GNULIB_POSIXCHECK +# undef dup2 +# define dup2(o,n) \ + (GL_LINK_WARNING ("dup2 is unportable - " \ + "use gnulib module dup2 for portability"), \ + dup2 (o, n)) +#endif + + +#if @GNULIB_FCHDIR@ +# if @REPLACE_FCHDIR@ + +/* Change the process' current working directory to the directory on which + the given file descriptor is open. + Return 0 if successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +extern int fchdir (int /*fd*/); + +# define close rpl_close +extern int close (int); +# define dup rpl_dup +extern int dup (int); +# define dup2 rpl_dup2 +extern int dup2 (int, int); + +# endif +#elif defined GNULIB_POSIXCHECK +# undef fchdir +# define fchdir(f) \ + (GL_LINK_WARNING ("fchdir is unportable - " \ + "use gnulib module fchdir for portability"), \ + fchdir (f)) +#endif + + +#if @GNULIB_FTRUNCATE@ +# if !@HAVE_FTRUNCATE@ +/* Change the size of the file to which FD is opened to become equal to LENGTH. + Return 0 if successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +extern int ftruncate (int fd, off_t length); +# endif +#elif defined GNULIB_POSIXCHECK +# undef ftruncate +# define ftruncate(f,l) \ + (GL_LINK_WARNING ("ftruncate is unportable - " \ + "use gnulib module ftruncate for portability"), \ + ftruncate (f, l)) +#endif + + +#if @GNULIB_GETCWD@ +/* Include the headers that might declare getcwd so that they will not + cause confusion if included after this file. */ +# include +# if @REPLACE_GETCWD@ +/* Get the name of the current working directory, and put it in SIZE bytes + of BUF. + Return BUF if successful, or NULL if the directory couldn't be determined + or SIZE was too small. + See the POSIX:2001 specification + . + Additionally, the gnulib module 'getcwd' guarantees the following GNU + extension: If BUF is NULL, an array is allocated with 'malloc'; the array + is SIZE bytes long, unless SIZE == 0, in which case it is as big as + necessary. */ +# define getcwd rpl_getcwd +extern char * getcwd (char *buf, size_t size); +# endif +#elif defined GNULIB_POSIXCHECK +# undef getcwd +# define getcwd(b,s) \ + (GL_LINK_WARNING ("getcwd is unportable - " \ + "use gnulib module getcwd for portability"), \ + getcwd (b, s)) +#endif + + +#if @GNULIB_GETLOGIN_R@ +/* Copies the user's login name to NAME. + The array pointed to by NAME has room for SIZE bytes. + + Returns 0 if successful. Upon error, an error number is returned, or -1 in + the case that the login name cannot be found but no specific error is + provided (this case is hopefully rare but is left open by the POSIX spec). + + See . + */ +# if !@HAVE_DECL_GETLOGIN_R@ +# include +extern int getlogin_r (char *name, size_t size); +# endif +#elif defined GNULIB_POSIXCHECK +# undef getlogin_r +# define getlogin_r(n,s) \ + (GL_LINK_WARNING ("getlogin_r is unportable - " \ + "use gnulib module getlogin_r for portability"), \ + getlogin_r (n, s)) +#endif + + +#if @GNULIB_GETPAGESIZE@ +# if !@HAVE_GETPAGESIZE@ +/* This is for POSIX systems. */ +# if !defined getpagesize && defined _SC_PAGESIZE +# if ! (defined __VMS && __VMS_VER < 70000000) +# define getpagesize() sysconf (_SC_PAGESIZE) +# endif +# endif +/* This is for older VMS. */ +# if !defined getpagesize && defined __VMS +# ifdef __ALPHA +# define getpagesize() 8192 +# else +# define getpagesize() 512 +# endif +# endif +/* This is for BeOS. */ +# if !defined getpagesize && @HAVE_OS_H@ +# include +# if defined B_PAGE_SIZE +# define getpagesize() B_PAGE_SIZE +# endif +# endif +/* This is for AmigaOS4.0. */ +# if !defined getpagesize && defined __amigaos4__ +# define getpagesize() 2048 +# endif +/* This is for older Unix systems. */ +# if !defined getpagesize && @HAVE_SYS_PARAM_H@ +# include +# ifdef EXEC_PAGESIZE +# define getpagesize() EXEC_PAGESIZE +# else +# ifdef NBPG +# ifndef CLSIZE +# define CLSIZE 1 +# endif +# define getpagesize() (NBPG * CLSIZE) +# else +# ifdef NBPC +# define getpagesize() NBPC +# endif +# endif +# endif +# endif +# endif +#elif defined GNULIB_POSIXCHECK +# undef getpagesize +# define getpagesize() \ + (GL_LINK_WARNING ("getpagesize is unportable - " \ + "use gnulib module getpagesize for portability"), \ + getpagesize ()) +#endif + + +#if @GNULIB_LCHOWN@ +# if @REPLACE_LCHOWN@ +/* Change the owner of FILE to UID (if UID is not -1) and the group of FILE + to GID (if GID is not -1). Do not follow symbolic links. + Return 0 if successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +# define lchown rpl_lchown +extern int lchown (char const *file, uid_t owner, gid_t group); +# endif +#elif defined GNULIB_POSIXCHECK +# undef lchown +# define lchown(f,u,g) \ + (GL_LINK_WARNING ("lchown is unportable to pre-POSIX.1-2001 " \ + "systems - use gnulib module lchown for portability"), \ + lchown (f, u, g)) +#endif + + +#if @GNULIB_LSEEK@ +# if @REPLACE_LSEEK@ +/* Set the offset of FD relative to SEEK_SET, SEEK_CUR, or SEEK_END. + Return the new offset if successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +# define lseek rpl_lseek + extern off_t lseek (int fd, off_t offset, int whence); +# endif +#elif defined GNULIB_POSIXCHECK +# undef lseek +# define lseek(f,o,w) \ + (GL_LINK_WARNING ("lseek does not fail with ESPIPE on pipes on some " \ + "systems - use gnulib module lseek for portability"), \ + lseek (f, o, w)) +#endif + + +#if @GNULIB_READLINK@ +/* Read the contents of the symbolic link FILE and place the first BUFSIZE + bytes of it into BUF. Return the number of bytes placed into BUF if + successful, otherwise -1 and errno set. + See the POSIX:2001 specification + . */ +# if !@HAVE_READLINK@ +# include +extern int readlink (const char *file, char *buf, size_t bufsize); +# endif +#elif defined GNULIB_POSIXCHECK +# undef readlink +# define readlink(f,b,s) \ + (GL_LINK_WARNING ("readlink is unportable - " \ + "use gnulib module readlink for portability"), \ + readlink (f, b, s)) +#endif + + +#if @GNULIB_SLEEP@ +/* Pause the execution of the current thread for N seconds. + Returns the number of seconds left to sleep. + See the POSIX:2001 specification + . */ +# if !@HAVE_SLEEP@ +extern unsigned int sleep (unsigned int n); +# endif +#elif defined GNULIB_POSIXCHECK +# undef sleep +# define sleep(n) \ + (GL_LINK_WARNING ("sleep is unportable - " \ + "use gnulib module sleep for portability"), \ + sleep (n)) +#endif + + +#ifdef __cplusplus +} +#endif + + +#endif /* _GL_UNISTD_H */ +#endif /* _GL_UNISTD_H */ diff --git a/src/bin/findutils/gnulib/lib/verify.h b/src/bin/findutils/gnulib/lib/verify.h new file mode 100644 index 0000000000..fac53f6fc4 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/verify.h @@ -0,0 +1,140 @@ +/* Compile-time assert-like macros. + + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Paul Eggert, Bruno Haible, and Jim Meyering. */ + +#ifndef VERIFY_H +# define VERIFY_H 1 + +/* Each of these macros verifies that its argument R is nonzero. To + be portable, R should be an integer constant expression. Unlike + assert (R), there is no run-time overhead. + + There are two macros, since no single macro can be used in all + contexts in C. verify_true (R) is for scalar contexts, including + integer constant expression contexts. verify (R) is for declaration + contexts, e.g., the top level. + + Symbols ending in "__" are private to this header. + + The code below uses several ideas. + + * The first step is ((R) ? 1 : -1). Given an expression R, of + integral or boolean or floating-point type, this yields an + expression of integral type, whose value is later verified to be + constant and nonnegative. + + * Next this expression W is wrapped in a type + struct verify_type__ { unsigned int verify_error_if_negative_size__: W; }. + If W is negative, this yields a compile-time error. No compiler can + deal with a bit-field of negative size. + + One might think that an array size check would have the same + effect, that is, that the type struct { unsigned int dummy[W]; } + would work as well. However, inside a function, some compilers + (such as C++ compilers and GNU C) allow local parameters and + variables inside array size expressions. With these compilers, + an array size check would not properly diagnose this misuse of + the verify macro: + + void function (int n) { verify (n < 0); } + + * For the verify macro, the struct verify_type__ will need to + somehow be embedded into a declaration. To be portable, this + declaration must declare an object, a constant, a function, or a + typedef name. If the declared entity uses the type directly, + such as in + + struct dummy {...}; + typedef struct {...} dummy; + extern struct {...} *dummy; + extern void dummy (struct {...} *); + extern struct {...} *dummy (void); + + two uses of the verify macro would yield colliding declarations + if the entity names are not disambiguated. A workaround is to + attach the current line number to the entity name: + + #define GL_CONCAT0(x, y) x##y + #define GL_CONCAT(x, y) GL_CONCAT0 (x, y) + extern struct {...} * GL_CONCAT(dummy,__LINE__); + + But this has the problem that two invocations of verify from + within the same macro would collide, since the __LINE__ value + would be the same for both invocations. + + A solution is to use the sizeof operator. It yields a number, + getting rid of the identity of the type. Declarations like + + extern int dummy [sizeof (struct {...})]; + extern void dummy (int [sizeof (struct {...})]); + extern int (*dummy (void)) [sizeof (struct {...})]; + + can be repeated. + + * Should the implementation use a named struct or an unnamed struct? + Which of the following alternatives can be used? + + extern int dummy [sizeof (struct {...})]; + extern int dummy [sizeof (struct verify_type__ {...})]; + extern void dummy (int [sizeof (struct {...})]); + extern void dummy (int [sizeof (struct verify_type__ {...})]); + extern int (*dummy (void)) [sizeof (struct {...})]; + extern int (*dummy (void)) [sizeof (struct verify_type__ {...})]; + + In the second and sixth case, the struct type is exported to the + outer scope; two such declarations therefore collide. GCC warns + about the first, third, and fourth cases. So the only remaining + possibility is the fifth case: + + extern int (*dummy (void)) [sizeof (struct {...})]; + + * This implementation exploits the fact that GCC does not warn about + the last declaration mentioned above. If a future version of GCC + introduces a warning for this, the problem could be worked around + by using code specialized to GCC, e.g.,: + + #if 4 <= __GNUC__ + # define verify(R) \ + extern int (* verify_function__ (void)) \ + [__builtin_constant_p (R) && (R) ? 1 : -1] + #endif + + * In C++, any struct definition inside sizeof is invalid. + Use a template type to work around the problem. */ + + +/* Verify requirement R at compile-time, as an integer constant expression. + Return 1. */ + +# ifdef __cplusplus +template + struct verify_type__ { unsigned int verify_error_if_negative_size__: w; }; +# define verify_true(R) \ + (!!sizeof (verify_type__<(R) ? 1 : -1>)) +# else +# define verify_true(R) \ + (!!sizeof \ + (struct { unsigned int verify_error_if_negative_size__: (R) ? 1 : -1; })) +# endif + +/* Verify requirement R at compile-time, as a declaration without a + trailing ';'. */ + +# define verify(R) extern int (* verify_function__ (void)) [verify_true (R)] + +#endif diff --git a/src/bin/findutils/gnulib/lib/wchar.in.h b/src/bin/findutils/gnulib/lib/wchar.in.h new file mode 100644 index 0000000000..b721572e72 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/wchar.in.h @@ -0,0 +1,82 @@ +/* A substitute for ISO C99 , for platforms that have issues. + + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* Written by Eric Blake. */ + +/* + * ISO C 99 for platforms that have issues. + * + * + * For now, this just ensures proper prerequisite inclusion order and + * the declaration of wcwidth(). + */ + +#ifndef _GL_WCHAR_H + +/* Tru64 with Desktop Toolkit C has a bug: must be included before + . + BSD/OS 4.0.1 has a bug: , and must be + included before . */ +#include +#include +#include + +/* Include the original if it exists. + Some builds of uClibc lack it. */ +/* The include_next requires a split double-inclusion guard. */ +#if @HAVE_WCHAR_H@ +# @INCLUDE_NEXT@ @NEXT_WCHAR_H@ +#endif + +#ifndef _GL_WCHAR_H +#define _GL_WCHAR_H + +/* The definition of GL_LINK_WARNING is copied here. */ + +#ifdef __cplusplus +extern "C" { +#endif + + +/* Return the number of screen columns needed for WC. */ +#if @GNULIB_WCWIDTH@ +# if @REPLACE_WCWIDTH@ +# undef wcwidth +# define wcwidth rpl_wcwidth +extern int wcwidth (wchar_t); +# else +# if !defined wcwidth && !@HAVE_DECL_WCWIDTH@ +/* wcwidth exists but is not declared. */ +extern int wcwidth (int /* actually wchar_t */); +# endif +# endif +#elif defined GNULIB_POSIXCHECK +# undef wcwidth +# define wcwidth(w) \ + (GL_LINK_WARNING ("wcwidth is unportable - " \ + "use gnulib module wcwidth for portability"), \ + wcwidth (w)) +#endif + + +#ifdef __cplusplus +} +#endif + +#endif /* _GL_WCHAR_H */ +#endif /* _GL_WCHAR_H */ diff --git a/src/bin/findutils/gnulib/lib/wctype.in.h b/src/bin/findutils/gnulib/lib/wctype.in.h new file mode 100644 index 0000000000..a86b5ad407 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/wctype.in.h @@ -0,0 +1,161 @@ +/* A substitute for ISO C99 , for platforms that lack it. + + Copyright (C) 2006, 2007 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* Written by Bruno Haible and Paul Eggert. */ + +/* + * ISO C 99 for platforms that lack it. + * + * + * iswctype, towctrans, towlower, towupper, wctrans, wctype, + * wctrans_t, and wctype_t are not yet implemented. + */ + +#ifndef _GL_WCTYPE_H + +#if @HAVE_WINT_T@ +/* Solaris 2.5 has a bug: must be included before . + Tru64 with Desktop Toolkit C has a bug: must be included before + . + BSD/OS 4.0.1 has a bug: , and must be + included before . */ +# include +# include +# include +# include +#endif + +/* Include the original if it exists. + BeOS 5 has the functions but no . */ +/* The include_next requires a split double-inclusion guard. */ +#if @HAVE_WCTYPE_H@ +# @INCLUDE_NEXT@ @NEXT_WCTYPE_H@ +#endif + +#ifndef _GL_WCTYPE_H +#define _GL_WCTYPE_H + +#if @HAVE_WINT_T@ +typedef wint_t __wctype_wint_t; +#else +typedef int __wctype_wint_t; +#endif + +/* FreeBSD 4.4 to 4.11 has but lacks the functions. + Assume all 12 functions are implemented the same way, or not at all. */ +#if ! @HAVE_ISWCNTRL@ + +/* IRIX 5.3 has macros but no functions, its isw* macros refer to an + undefined variable _ctmp_ and to macros like _P, and they + refer to system functions like _iswctype that are not in the + standard C library. Rather than try to get ancient buggy + implementations like this to work, just disable them. */ +# undef iswalnum +# undef iswalpha +# undef iswblank +# undef iswcntrl +# undef iswdigit +# undef iswgraph +# undef iswlower +# undef iswprint +# undef iswpunct +# undef iswspace +# undef iswupper +# undef iswxdigit + +static inline int +iswalnum (__wctype_wint_t wc) +{ + return ((wc >= '0' && wc <= '9') + || ((wc & ~0x20) >= 'A' && (wc & ~0x20) <= 'Z')); +} + +static inline int +iswalpha (__wctype_wint_t wc) +{ + return (wc & ~0x20) >= 'A' && (wc & ~0x20) <= 'Z'; +} + +static inline int +iswblank (__wctype_wint_t wc) +{ + return wc == ' ' || wc == '\t'; +} + +static inline int +iswcntrl (__wctype_wint_t wc) +{ + return (wc & ~0x1f) == 0 || wc == 0x7f; +} + +static inline int +iswdigit (__wctype_wint_t wc) +{ + return wc >= '0' && wc <= '9'; +} + +static inline int +iswgraph (__wctype_wint_t wc) +{ + return wc >= '!' && wc <= '~'; +} + +static inline int +iswlower (__wctype_wint_t wc) +{ + return wc >= 'a' && wc <= 'z'; +} + +static inline int +iswprint (__wctype_wint_t wc) +{ + return wc >= ' ' && wc <= '~'; +} + +static inline int +iswpunct (__wctype_wint_t wc) +{ + return (wc >= '!' && wc <= '~' + && !((wc >= '0' && wc <= '9') + || ((wc & ~0x20) >= 'A' && (wc & ~0x20) <= 'Z'))); +} + +static inline int +iswspace (__wctype_wint_t wc) +{ + return (wc == ' ' || wc == '\t' + || wc == '\n' || wc == '\v' || wc == '\f' || wc == '\r'); +} + +static inline int +iswupper (__wctype_wint_t wc) +{ + return wc >= 'A' && wc <= 'Z'; +} + +static inline int +iswxdigit (__wctype_wint_t wc) +{ + return ((wc >= '0' && wc <= '9') + || ((wc & ~0x20) >= 'A' && (wc & ~0x20) <= 'F')); +} + +# endif /* ! HAVE_ISWCNTRL */ + +#endif /* _GL_WCTYPE_H */ +#endif /* _GL_WCTYPE_H */ diff --git a/src/bin/findutils/gnulib/lib/xalloc-die.c b/src/bin/findutils/gnulib/lib/xalloc-die.c new file mode 100644 index 0000000000..0a0694fcfe --- /dev/null +++ b/src/bin/findutils/gnulib/lib/xalloc-die.c @@ -0,0 +1,41 @@ +/* Report a memory allocation failure and exit. + + Copyright (C) 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2006 Free + Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "xalloc.h" + +#include + +#include "error.h" +#include "exitfail.h" + +#include "gettext.h" +#define _(msgid) gettext (msgid) + +void +xalloc_die (void) +{ + error (exit_failure, 0, "%s", _("memory exhausted")); + + /* The `noreturn' cannot be given to error, since it may return if + its first argument is 0. To help compilers understand the + xalloc_die does not return, call abort. Also, the abort is a + safety feature if exit_failure is 0 (which shouldn't happen). */ + abort (); +} diff --git a/src/bin/findutils/gnulib/lib/xalloc.h b/src/bin/findutils/gnulib/lib/xalloc.h new file mode 100644 index 0000000000..9c40d7264d --- /dev/null +++ b/src/bin/findutils/gnulib/lib/xalloc.h @@ -0,0 +1,270 @@ +/* xalloc.h -- malloc with out-of-memory checking + + Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, + 1999, 2000, 2003, 2004, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef XALLOC_H_ +# define XALLOC_H_ + +# include + + +# ifdef __cplusplus +extern "C" { +# endif + + +# ifndef __attribute__ +# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__ +# define __attribute__(x) +# endif +# endif + +# ifndef ATTRIBUTE_NORETURN +# define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__)) +# endif + +/* This function is always triggered when memory is exhausted. + It must be defined by the application, either explicitly + or by using gnulib's xalloc-die module. This is the + function to call when one wants the program to die because of a + memory allocation failure. */ +extern void xalloc_die (void) ATTRIBUTE_NORETURN; + +void *xmalloc (size_t s); +void *xzalloc (size_t s); +void *xcalloc (size_t n, size_t s); +void *xrealloc (void *p, size_t s); +void *x2realloc (void *p, size_t *pn); +void *xmemdup (void const *p, size_t s); +char *xstrdup (char const *str); + +/* Return 1 if an array of N objects, each of size S, cannot exist due + to size arithmetic overflow. S must be positive and N must be + nonnegative. This is a macro, not an inline function, so that it + works correctly even when SIZE_MAX < N. + + By gnulib convention, SIZE_MAX represents overflow in size + calculations, so the conservative dividend to use here is + SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value. + However, malloc (SIZE_MAX) fails on all known hosts where + sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for + exactly-SIZE_MAX allocations on such hosts; this avoids a test and + branch when S is known to be 1. */ +# define xalloc_oversized(n, s) \ + ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n)) + + +/* In the following macros, T must be an elementary or structure/union or + typedef'ed type, or a pointer to such a type. To apply one of the + following macros to a function pointer or array type, you need to typedef + it first and use the typedef name. */ + +/* Allocate an object of type T dynamically, with error checking. */ +/* extern t *XMALLOC (typename t); */ +# define XMALLOC(t) ((t *) xmalloc (sizeof (t))) + +/* Allocate memory for N elements of type T, with error checking. */ +/* extern t *XNMALLOC (size_t n, typename t); */ +# define XNMALLOC(n, t) \ + ((t *) (sizeof (t) == 1 ? xmalloc (n) : xnmalloc (n, sizeof (t)))) + +/* Allocate an object of type T dynamically, with error checking, + and zero it. */ +/* extern t *XZALLOC (typename t); */ +# define XZALLOC(t) ((t *) xzalloc (sizeof (t))) + +/* Allocate memory for N elements of type T, with error checking, + and zero it. */ +/* extern t *XCALLOC (size_t n, typename t); */ +# define XCALLOC(n, t) \ + ((t *) (sizeof (t) == 1 ? xzalloc (n) : xcalloc (n, sizeof (t)))) + + +# if HAVE_INLINE +# define static_inline static inline +# else + void *xnmalloc (size_t n, size_t s); + void *xnrealloc (void *p, size_t n, size_t s); + void *x2nrealloc (void *p, size_t *pn, size_t s); + char *xcharalloc (size_t n); +# endif + +# ifdef static_inline + +/* Allocate an array of N objects, each with S bytes of memory, + dynamically, with error checking. S must be nonzero. */ + +static_inline void * +xnmalloc (size_t n, size_t s) +{ + if (xalloc_oversized (n, s)) + xalloc_die (); + return xmalloc (n * s); +} + +/* Change the size of an allocated block of memory P to an array of N + objects each of S bytes, with error checking. S must be nonzero. */ + +static_inline void * +xnrealloc (void *p, size_t n, size_t s) +{ + if (xalloc_oversized (n, s)) + xalloc_die (); + return xrealloc (p, n * s); +} + +/* If P is null, allocate a block of at least *PN such objects; + otherwise, reallocate P so that it contains more than *PN objects + each of S bytes. *PN must be nonzero unless P is null, and S must + be nonzero. Set *PN to the new number of objects, and return the + pointer to the new block. *PN is never set to zero, and the + returned pointer is never null. + + Repeated reallocations are guaranteed to make progress, either by + allocating an initial block with a nonzero size, or by allocating a + larger block. + + In the following implementation, nonzero sizes are increased by a + factor of approximately 1.5 so that repeated reallocations have + O(N) overall cost rather than O(N**2) cost, but the + specification for this function does not guarantee that rate. + + Here is an example of use: + + int *p = NULL; + size_t used = 0; + size_t allocated = 0; + + void + append_int (int value) + { + if (used == allocated) + p = x2nrealloc (p, &allocated, sizeof *p); + p[used++] = value; + } + + This causes x2nrealloc to allocate a block of some nonzero size the + first time it is called. + + To have finer-grained control over the initial size, set *PN to a + nonzero value before calling this function with P == NULL. For + example: + + int *p = NULL; + size_t used = 0; + size_t allocated = 0; + size_t allocated1 = 1000; + + void + append_int (int value) + { + if (used == allocated) + { + p = x2nrealloc (p, &allocated1, sizeof *p); + allocated = allocated1; + } + p[used++] = value; + } + + */ + +static_inline void * +x2nrealloc (void *p, size_t *pn, size_t s) +{ + size_t n = *pn; + + if (! p) + { + if (! n) + { + /* The approximate size to use for initial small allocation + requests, when the invoking code specifies an old size of + zero. 64 bytes is the largest "small" request for the + GNU C library malloc. */ + enum { DEFAULT_MXFAST = 64 }; + + n = DEFAULT_MXFAST / s; + n += !n; + } + } + else + { + /* Set N = ceil (1.5 * N) so that progress is made if N == 1. + Check for overflow, so that N * S stays in size_t range. + The check is slightly conservative, but an exact check isn't + worth the trouble. */ + if ((size_t) -1 / 3 * 2 / s <= n) + xalloc_die (); + n += (n + 1) / 2; + } + + *pn = n; + return xrealloc (p, n * s); +} + +/* Return a pointer to a new buffer of N bytes. This is like xmalloc, + except it returns char *. */ + +static_inline char * +xcharalloc (size_t n) +{ + return XNMALLOC (n, char); +} + +# endif + +# ifdef __cplusplus +} + +/* C++ does not allow conversions from void * to other pointer types + without a cast. Use templates to work around the problem when + possible. */ + +template inline T * +xrealloc (T *p, size_t s) +{ + return (T *) xrealloc ((void *) p, s); +} + +template inline T * +xnrealloc (T *p, size_t n, size_t s) +{ + return (T *) xnrealloc ((void *) p, n, s); +} + +template inline T * +x2realloc (T *p, size_t *pn) +{ + return (T *) x2realloc ((void *) p, pn); +} + +template inline T * +x2nrealloc (T *p, size_t *pn, size_t s) +{ + return (T *) x2nrealloc ((void *) p, pn, s); +} + +template inline T * +xmemdup (T const *p, size_t s) +{ + return (T *) xmemdup ((void const *) p, s); +} + +# endif + + +#endif /* !XALLOC_H_ */ diff --git a/src/bin/findutils/gnulib/lib/xgetcwd.c b/src/bin/findutils/gnulib/lib/xgetcwd.c new file mode 100644 index 0000000000..6787b4653c --- /dev/null +++ b/src/bin/findutils/gnulib/lib/xgetcwd.c @@ -0,0 +1,40 @@ +/* xgetcwd.c -- return current directory with unlimited length + + Copyright (C) 2001, 2003, 2004, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Jim Meyering. */ + +#include + +#include "xgetcwd.h" + +#include +#include + +#include "xalloc.h" + +/* Return the current directory, newly allocated. + Upon an out-of-memory error, call xalloc_die. + Upon any other type of error, return NULL. */ + +char * +xgetcwd (void) +{ + char *cwd = getcwd (NULL, 0); + if (! cwd && errno == ENOMEM) + xalloc_die (); + return cwd; +} diff --git a/src/bin/findutils/gnulib/lib/xgetcwd.h b/src/bin/findutils/gnulib/lib/xgetcwd.h new file mode 100644 index 0000000000..3d966de967 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/xgetcwd.h @@ -0,0 +1,17 @@ +/* prototype for xgetcwd + Copyright (C) 1995, 2001, 2003 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +extern char *xgetcwd (void); diff --git a/src/bin/findutils/gnulib/lib/xmalloc.c b/src/bin/findutils/gnulib/lib/xmalloc.c new file mode 100644 index 0000000000..3a12345743 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/xmalloc.c @@ -0,0 +1,122 @@ +/* xmalloc.c -- malloc with out of memory checking + + Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, + 1999, 2000, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, + Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#if ! HAVE_INLINE +# define static_inline +#endif +#include "xalloc.h" +#undef static_inline + +#include +#include + +#ifndef SIZE_MAX +# define SIZE_MAX ((size_t) -1) +#endif + +/* 1 if calloc is known to be compatible with GNU calloc. This + matters if we are not also using the calloc module, which defines + HAVE_CALLOC and supports the GNU API even on non-GNU platforms. */ +#if defined HAVE_CALLOC || defined __GLIBC__ +enum { HAVE_GNU_CALLOC = 1 }; +#else +enum { HAVE_GNU_CALLOC = 0 }; +#endif + +/* Allocate N bytes of memory dynamically, with error checking. */ + +void * +xmalloc (size_t n) +{ + void *p = malloc (n); + if (!p && n != 0) + xalloc_die (); + return p; +} + +/* Change the size of an allocated block of memory P to N bytes, + with error checking. */ + +void * +xrealloc (void *p, size_t n) +{ + p = realloc (p, n); + if (!p && n != 0) + xalloc_die (); + return p; +} + +/* If P is null, allocate a block of at least *PN bytes; otherwise, + reallocate P so that it contains more than *PN bytes. *PN must be + nonzero unless P is null. Set *PN to the new block's size, and + return the pointer to the new block. *PN is never set to zero, and + the returned pointer is never null. */ + +void * +x2realloc (void *p, size_t *pn) +{ + return x2nrealloc (p, pn, 1); +} + +/* Allocate S bytes of zeroed memory dynamically, with error checking. + There's no need for xnzalloc (N, S), since it would be equivalent + to xcalloc (N, S). */ + +void * +xzalloc (size_t s) +{ + return memset (xmalloc (s), 0, s); +} + +/* Allocate zeroed memory for N elements of S bytes, with error + checking. S must be nonzero. */ + +void * +xcalloc (size_t n, size_t s) +{ + void *p; + /* Test for overflow, since some calloc implementations don't have + proper overflow checks. But omit overflow and size-zero tests if + HAVE_GNU_CALLOC, since GNU calloc catches overflow and never + returns NULL if successful. */ + if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s)) + || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0))) + xalloc_die (); + return p; +} + +/* Clone an object P of size S, with error checking. There's no need + for xnmemdup (P, N, S), since xmemdup (P, N * S) works without any + need for an arithmetic overflow check. */ + +void * +xmemdup (void const *p, size_t s) +{ + return memcpy (xmalloc (s), p, s); +} + +/* Clone STRING. */ + +char * +xstrdup (char const *string) +{ + return xmemdup (string, strlen (string) + 1); +} diff --git a/src/bin/findutils/gnulib/lib/xstrndup.c b/src/bin/findutils/gnulib/lib/xstrndup.c new file mode 100644 index 0000000000..37488cd99d --- /dev/null +++ b/src/bin/findutils/gnulib/lib/xstrndup.c @@ -0,0 +1,36 @@ +/* Duplicate a bounded initial segment of a string, with out-of-memory + checking. + Copyright (C) 2003, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +/* Specification. */ +#include "xstrndup.h" + +#include +#include "xalloc.h" + +/* Return a newly allocated copy of at most N bytes of STRING. + In other words, return a copy of the initial segment of length N of + STRING. */ +char * +xstrndup (const char *string, size_t n) +{ + char *s = strndup (string, n); + if (! s) + xalloc_die (); + return s; +} diff --git a/src/bin/findutils/gnulib/lib/xstrndup.h b/src/bin/findutils/gnulib/lib/xstrndup.h new file mode 100644 index 0000000000..4882e39475 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/xstrndup.h @@ -0,0 +1,23 @@ +/* Duplicate a bounded initial segment of a string, with out-of-memory + checking. + Copyright (C) 2003 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +/* Return a newly allocated copy of at most N bytes of STRING. + In other words, return a copy of the initial segment of length N of + STRING. */ +extern char *xstrndup (const char *string, size_t n); diff --git a/src/bin/findutils/gnulib/lib/xstrtol-error.c b/src/bin/findutils/gnulib/lib/xstrtol-error.c new file mode 100644 index 0000000000..8d5718d8d8 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/xstrtol-error.c @@ -0,0 +1,98 @@ +/* A more useful interface to strtol. + + Copyright (C) 1995, 1996, 1998, 1999, 2001, 2002, 2003, 2004, 2006, 2007 + Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include +#include "xstrtol.h" + +#include + +#include "error.h" +#include "exitfail.h" +#include "gettext.h" + +#define N_(msgid) msgid + +/* Report an error for an invalid integer in an option argument. + + ERR is the error code returned by one of the xstrto* functions. + + Use OPT_IDX to decide whether to print the short option string "C" + or "-C" or a long option string derived from LONG_OPTION. OPT_IDX + is -2 if the short option "C" was used, without any leading "-"; it + is -1 if the short option "-C" was used; otherwise it is an index + into LONG_OPTIONS, which should have a name preceded by two '-' + characters. + + ARG is the option-argument containing the integer. + + After reporting an error, exit with status EXIT_STATUS if it is + nonzero. */ + +static void +xstrtol_error (enum strtol_error err, + int opt_idx, char c, struct option const *long_options, + char const *arg, + int exit_status) +{ + char const *hyphens = "--"; + char const *msgid; + char const *option; + char option_buffer[2]; + + switch (err) + { + default: + abort (); + + case LONGINT_INVALID: + msgid = N_("invalid %s%s argument `%s'"); + break; + + case LONGINT_INVALID_SUFFIX_CHAR: + case LONGINT_INVALID_SUFFIX_CHAR_WITH_OVERFLOW: + msgid = N_("invalid suffix in %s%s argument `%s'"); + break; + + case LONGINT_OVERFLOW: + msgid = N_("%s%s argument `%s' too large"); + break; + } + + if (opt_idx < 0) + { + hyphens -= opt_idx; + option_buffer[0] = c; + option_buffer[1] = '\0'; + option = option_buffer; + } + else + option = long_options[opt_idx].name; + + error (exit_failure, 0, gettext (msgid), hyphens, option, arg); +} + +/* Like xstrtol_error, except exit with a failure status. */ + +void +xstrtol_fatal (enum strtol_error err, + int opt_idx, char c, struct option const *long_options, + char const *arg) +{ + xstrtol_error (err, opt_idx, c, long_options, arg, exit_failure); + abort (); +} diff --git a/src/bin/findutils/gnulib/lib/xstrtol.c b/src/bin/findutils/gnulib/lib/xstrtol.c new file mode 100644 index 0000000000..1804fe5866 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/xstrtol.c @@ -0,0 +1,228 @@ +/* A more useful interface to strtol. + + Copyright (C) 1995, 1996, 1998, 1999, 2000, 2001, 2003, 2004, 2005, + 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Jim Meyering. */ + +#ifndef __strtol +# define __strtol strtol +# define __strtol_t long int +# define __xstrtol xstrtol +# define STRTOL_T_MINIMUM LONG_MIN +# define STRTOL_T_MAXIMUM LONG_MAX +#endif + +#include + +#include "xstrtol.h" + +/* Some pre-ANSI implementations (e.g. SunOS 4) + need stderr defined if assertion checking is enabled. */ +#include + +#include +#include +#include +#include +#include +#include + +#include "intprops.h" + +static strtol_error +bkm_scale (__strtol_t *x, int scale_factor) +{ + if (TYPE_SIGNED (__strtol_t) && *x < STRTOL_T_MINIMUM / scale_factor) + { + *x = STRTOL_T_MINIMUM; + return LONGINT_OVERFLOW; + } + if (STRTOL_T_MAXIMUM / scale_factor < *x) + { + *x = STRTOL_T_MAXIMUM; + return LONGINT_OVERFLOW; + } + *x *= scale_factor; + return LONGINT_OK; +} + +static strtol_error +bkm_scale_by_power (__strtol_t *x, int base, int power) +{ + strtol_error err = LONGINT_OK; + while (power--) + err |= bkm_scale (x, base); + return err; +} + +/* FIXME: comment. */ + +strtol_error +__xstrtol (const char *s, char **ptr, int strtol_base, + __strtol_t *val, const char *valid_suffixes) +{ + char *t_ptr; + char **p; + __strtol_t tmp; + strtol_error err = LONGINT_OK; + + assert (0 <= strtol_base && strtol_base <= 36); + + p = (ptr ? ptr : &t_ptr); + + if (! TYPE_SIGNED (__strtol_t)) + { + const char *q = s; + unsigned char ch = *q; + while (isspace (ch)) + ch = *++q; + if (ch == '-') + return LONGINT_INVALID; + } + + errno = 0; + tmp = __strtol (s, p, strtol_base); + + if (*p == s) + { + /* If there is no number but there is a valid suffix, assume the + number is 1. The string is invalid otherwise. */ + if (valid_suffixes && **p && strchr (valid_suffixes, **p)) + tmp = 1; + else + return LONGINT_INVALID; + } + else if (errno != 0) + { + if (errno != ERANGE) + return LONGINT_INVALID; + err = LONGINT_OVERFLOW; + } + + /* Let valid_suffixes == NULL mean `allow any suffix'. */ + /* FIXME: update all callers except the ones that allow suffixes + after the number, changing last parameter NULL to `""'. */ + if (!valid_suffixes) + { + *val = tmp; + return err; + } + + if (**p != '\0') + { + int base = 1024; + int suffixes = 1; + strtol_error overflow; + + if (!strchr (valid_suffixes, **p)) + { + *val = tmp; + return err | LONGINT_INVALID_SUFFIX_CHAR; + } + + if (strchr (valid_suffixes, '0')) + { + /* The ``valid suffix'' '0' is a special flag meaning that + an optional second suffix is allowed, which can change + the base. A suffix "B" (e.g. "100MB") stands for a power + of 1000, whereas a suffix "iB" (e.g. "100MiB") stands for + a power of 1024. If no suffix (e.g. "100M"), assume + power-of-1024. */ + + switch (p[0][1]) + { + case 'i': + if (p[0][2] == 'B') + suffixes += 2; + break; + + case 'B': + case 'D': /* 'D' is obsolescent */ + base = 1000; + suffixes++; + break; + } + } + + switch (**p) + { + case 'b': + overflow = bkm_scale (&tmp, 512); + break; + + case 'B': + overflow = bkm_scale (&tmp, 1024); + break; + + case 'c': + overflow = 0; + break; + + case 'E': /* exa or exbi */ + overflow = bkm_scale_by_power (&tmp, base, 6); + break; + + case 'G': /* giga or gibi */ + case 'g': /* 'g' is undocumented; for compatibility only */ + overflow = bkm_scale_by_power (&tmp, base, 3); + break; + + case 'k': /* kilo */ + case 'K': /* kibi */ + overflow = bkm_scale_by_power (&tmp, base, 1); + break; + + case 'M': /* mega or mebi */ + case 'm': /* 'm' is undocumented; for compatibility only */ + overflow = bkm_scale_by_power (&tmp, base, 2); + break; + + case 'P': /* peta or pebi */ + overflow = bkm_scale_by_power (&tmp, base, 5); + break; + + case 'T': /* tera or tebi */ + case 't': /* 't' is undocumented; for compatibility only */ + overflow = bkm_scale_by_power (&tmp, base, 4); + break; + + case 'w': + overflow = bkm_scale (&tmp, 2); + break; + + case 'Y': /* yotta or 2**80 */ + overflow = bkm_scale_by_power (&tmp, base, 8); + break; + + case 'Z': /* zetta or 2**70 */ + overflow = bkm_scale_by_power (&tmp, base, 7); + break; + + default: + *val = tmp; + return err | LONGINT_INVALID_SUFFIX_CHAR; + } + + err |= overflow; + *p += suffixes; + if (**p) + err |= LONGINT_INVALID_SUFFIX_CHAR; + } + + *val = tmp; + return err; +} diff --git a/src/bin/findutils/gnulib/lib/xstrtol.h b/src/bin/findutils/gnulib/lib/xstrtol.h new file mode 100644 index 0000000000..d96e34a062 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/xstrtol.h @@ -0,0 +1,78 @@ +/* A more useful interface to strtol. + + Copyright (C) 1995, 1996, 1998, 1999, 2001, 2002, 2003, 2004, 2006, 2007 + Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef XSTRTOL_H_ +# define XSTRTOL_H_ 1 + +# include +# include + +# ifndef _STRTOL_ERROR +enum strtol_error + { + LONGINT_OK = 0, + + /* These two values can be ORed together, to indicate that both + errors occurred. */ + LONGINT_OVERFLOW = 1, + LONGINT_INVALID_SUFFIX_CHAR = 2, + + LONGINT_INVALID_SUFFIX_CHAR_WITH_OVERFLOW = (LONGINT_INVALID_SUFFIX_CHAR + | LONGINT_OVERFLOW), + LONGINT_INVALID = 4 + }; +typedef enum strtol_error strtol_error; +# endif + +# define _DECLARE_XSTRTOL(name, type) \ + strtol_error name (const char *, char **, int, type *, const char *); +_DECLARE_XSTRTOL (xstrtol, long int) +_DECLARE_XSTRTOL (xstrtoul, unsigned long int) +_DECLARE_XSTRTOL (xstrtoimax, intmax_t) +_DECLARE_XSTRTOL (xstrtoumax, uintmax_t) + +#ifndef __attribute__ +# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__ +# define __attribute__(x) +# endif +#endif + +#ifndef ATTRIBUTE_NORETURN +# define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__)) +#endif + +/* Report an error for an invalid integer in an option argument. + + ERR is the error code returned by one of the xstrto* functions. + + Use OPT_IDX to decide whether to print the short option string "C" + or "-C" or a long option string derived from LONG_OPTION. OPT_IDX + is -2 if the short option "C" was used, without any leading "-"; it + is -1 if the short option "-C" was used; otherwise it is an index + into LONG_OPTIONS, which should have a name preceded by two '-' + characters. + + ARG is the option-argument containing the integer. + + After reporting an error, exit with a failure status. */ + +void xstrtol_fatal (enum strtol_error, + int, char, struct option const *, + char const *) ATTRIBUTE_NORETURN; + +#endif /* not XSTRTOL_H_ */ diff --git a/src/bin/findutils/gnulib/lib/xstrtoul.c b/src/bin/findutils/gnulib/lib/xstrtoul.c new file mode 100644 index 0000000000..285f7b96f8 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/xstrtoul.c @@ -0,0 +1,6 @@ +#define __strtol strtoul +#define __strtol_t unsigned long int +#define __xstrtol xstrtoul +#define STRTOL_T_MINIMUM 0 +#define STRTOL_T_MAXIMUM ULONG_MAX +#include "xstrtol.c" diff --git a/src/bin/findutils/gnulib/lib/xstrtoumax.c b/src/bin/findutils/gnulib/lib/xstrtoumax.c new file mode 100644 index 0000000000..9a2349f00d --- /dev/null +++ b/src/bin/findutils/gnulib/lib/xstrtoumax.c @@ -0,0 +1,6 @@ +#define __strtol strtoumax +#define __strtol_t uintmax_t +#define __xstrtol xstrtoumax +#define STRTOL_T_MINIMUM 0 +#define STRTOL_T_MAXIMUM UINTMAX_MAX +#include "xstrtol.c" diff --git a/src/bin/findutils/gnulib/lib/yesno.c b/src/bin/findutils/gnulib/lib/yesno.c new file mode 100644 index 0000000000..05bf80e852 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/yesno.c @@ -0,0 +1,63 @@ +/* yesno.c -- read a yes/no response from stdin + + Copyright (C) 1990, 1998, 2001, 2003, 2004, 2005, 2006, 2007 Free + Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include "yesno.h" + +#include +#include + +extern int rpmatch (char const *response); + +/* Return true if we read an affirmative line from standard input. + + Since this function uses stdin, it is suggested that the caller not + use STDIN_FILENO directly, and also that the line + atexit(close_stdin) be added to main(). */ + +bool +yesno (void) +{ + bool yes; + +#if ENABLE_NLS + char *response = NULL; + size_t response_size = 0; + ssize_t response_len = getline (&response, &response_size, stdin); + + if (response_len <= 0) + yes = false; + else + { + response[response_len - 1] = '\0'; + yes = (0 < rpmatch (response)); + } + + free (response); +#else + /* Test against "^[yY]", hardcoded to avoid requiring getline, + regex, and rpmatch. */ + int c = getchar (); + yes = (c == 'y' || c == 'Y'); + while (c != '\n' && c != EOF) + c = getchar (); +#endif + + return yes; +} diff --git a/src/bin/findutils/gnulib/lib/yesno.h b/src/bin/findutils/gnulib/lib/yesno.h new file mode 100644 index 0000000000..633c274a64 --- /dev/null +++ b/src/bin/findutils/gnulib/lib/yesno.h @@ -0,0 +1,24 @@ +/* declare yesno + Copyright (C) 2004 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#ifndef YESNO_H_ +# define YESNO_H_ + +# include + +bool yesno (void); + +#endif diff --git a/src/bin/findutils/lib/Jamfile b/src/bin/findutils/lib/Jamfile index d07069e688..ab4da269c3 100644 --- a/src/bin/findutils/lib/Jamfile +++ b/src/bin/findutils/lib/Jamfile @@ -1,5 +1,6 @@ SubDir HAIKU_TOP src bin findutils lib ; +SubDirSysHdrs [ FDirName $(SUBDIR) $(DOTDOT) gnulib lib ] ; SubDirSysHdrs [ FDirName $(SUBDIR) $(DOTDOT) ] ; # filter warnings we don't want here @@ -8,28 +9,20 @@ TARGET_WARNING_CCFLAGS = [ FFilter $(TARGET_WARNING_CCFLAGS) # set some additional defines { - SubDirCcFlags -DHAVE_CONFIG_H ; + SubDirCcFlags -DHAVE_CONFIG_H -DVERSION='\"4.2.33\"' ; } StaticLibrary libfindutils.a : - regex.c - dirname.c - error.c - filemode.c - getopt.c - getopt1.c - idcache.c + buildcmd.c + extendbuf.c + gnulib-version.c listfile.c - modechange.c nextelem.c - savedir.c - xmalloc.c - getline.c - xstrdup.c - xgetcwd.c - fnmatch.c - fileblocks.c + printquoted.c + qmark.c + regextype.c + savedirinfo.c version.c ; diff --git a/src/bin/findutils/lib/buildcmd.c b/src/bin/findutils/lib/buildcmd.c new file mode 100644 index 0000000000..3cc1501794 --- /dev/null +++ b/src/bin/findutils/lib/buildcmd.c @@ -0,0 +1,513 @@ +/* buildcmd.c -- build command lines from a list of arguments. + Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2005, 2006, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include + +# ifndef PARAMS +# if defined PROTOTYPES || (defined __STDC__ && __STDC__) +# define PARAMS(Args) Args +# else +# define PARAMS(Args) () +# endif +# endif + +#if defined(HAVE_STRING_H) || defined(STDC_HEADERS) +#include +#endif + + +#if DO_MULTIBYTE +# if HAVE_MBRLEN +# include +# else + /* Simulate mbrlen with mblen as best we can. */ +# define mbstate_t int +# define mbrlen(s, n, ps) mblen (s, n) +# endif +#endif + +#ifdef HAVE_LOCALE_H +#include +#endif +#if ENABLE_NLS +# include +# define _(Text) gettext (Text) +#else +# define _(Text) Text +#define textdomain(Domain) +#define bindtextdomain(Package, Directory) +#endif +#ifdef gettext_noop +# define N_(String) gettext_noop (String) +#else +/* See locate.c for explanation as to why not use (String) */ +# define N_(String) String +#endif + +#ifndef _POSIX_SOURCE +#include +#endif + +#ifdef HAVE_LIMITS_H +#include +#endif + +/* The presence of unistd.h is assumed by gnulib these days, so we + * might as well assume it too. + */ +/* for sysconf() */ +#include + +#include + +/* COMPAT: SYSV version defaults size (and has a max value of) to 470. + We try to make it as large as possible. */ +#if !defined(ARG_MAX) && defined(_SC_ARG_MAX) +#define ARG_MAX sysconf (_SC_ARG_MAX) +#endif +#ifndef ARG_MAX +#define ARG_MAX NCARGS +#endif + + + +#include +#include + +#include "buildcmd.h" + + +extern char **environ; + + +static char *mbstrstr PARAMS ((const char *haystack, const char *needle)); + +/* Replace all instances of `replace_pat' in ARG with `linebuf', + and add the resulting string to the list of arguments for the command + to execute. + ARGLEN is the length of ARG, not including the null. + LBLEN is the length of LINEBUF, not including the null. + PFXLEN is the length of PREFIX. Substitution is not performed on + the prefix. The prefix is used if the argument contains replace_pat. + + COMPAT: insertions on the SYSV version are limited to 255 chars per line, + and a max of 5 occurrences of replace_pat in the initial-arguments. + Those restrictions do not exist here. */ + +void +bc_do_insert (const struct buildcmd_control *ctl, + struct buildcmd_state *state, + char *arg, size_t arglen, + const char *prefix, size_t pfxlen, + const char *linebuf, size_t lblen, + int initial_args) +{ + /* Temporary copy of each arg with the replace pattern replaced by the + real arg. */ + static char *insertbuf; + char *p; + size_t bytes_left = ctl->arg_max - 1; /* Bytes left on the command line. */ + int need_prefix; + + /* XXX: on systems lacking an upper limit for exec args, ctl->arg_max + * may have been set to LONG_MAX (see bc_get_arg_max()). Hence + * this xmalloc call may be a bad idea, especially since we are + * adding 1 to it... + */ + if (!insertbuf) + insertbuf = (char *) xmalloc (ctl->arg_max + 1); + p = insertbuf; + + do + { + size_t len; /* Length in ARG before `replace_pat'. */ + char *s = mbstrstr (arg, ctl->replace_pat); + if (s) + { + len = s - arg; + } + else + { + len = arglen; + } + + if (bytes_left <= len) + break; + else + bytes_left -= len; + + strncpy (p, arg, len); + p += len; + arg += len; + arglen -= len; + + if (s) + { + if (bytes_left <= (lblen + pfxlen)) + break; + else + bytes_left -= (lblen + pfxlen); + + if (prefix) + { + strcpy (p, prefix); + p += pfxlen; + } + strcpy (p, linebuf); + p += lblen; + + arg += ctl->rplen; + arglen -= ctl->rplen; + } + } + while (*arg); + if (*arg) + error (1, 0, _("command too long")); + *p++ = '\0'; + + bc_push_arg (ctl, state, + insertbuf, p - insertbuf, + NULL, 0, + initial_args); +} + +static +void do_exec(const struct buildcmd_control *ctl, + struct buildcmd_state *state) +{ + (ctl->exec_callback)(ctl, state); +} + + +/* Return nonzero if there would not be enough room for an additional + * argument. We check the total number of arguments only, not the space + * occupied by those arguments. + * + * If we return zero, there still may not be enough room for the next + * argument, depending on its length. + */ +static int +bc_argc_limit_reached(int initial_args, + const struct buildcmd_control *ctl, + struct buildcmd_state *state) +{ + /* Check to see if we about to exceed a limit set by xargs' -n option */ + if (!initial_args && ctl->args_per_exec && + ( (state->cmd_argc - ctl->initial_argc) == ctl->args_per_exec)) + return 1; + + /* We deliberately use an equality test here rather than >= in order + * to force a software failure if the code is modified in such a way + * that it fails to call this function for every new argument. + */ + return state->cmd_argc == ctl->max_arg_count; +} + + +/* Add ARG to the end of the list of arguments `cmd_argv' to pass + to the command. + LEN is the length of ARG, including the terminating null. + If this brings the list up to its maximum size, execute the command. */ + +void +bc_push_arg (const struct buildcmd_control *ctl, + struct buildcmd_state *state, + const char *arg, size_t len, + const char *prefix, size_t pfxlen, + int initial_args) +{ + if (!initial_args) + state->todo = 1; + + if (arg) + { + if (state->cmd_argv_chars + len > ctl->arg_max) + { + if (initial_args || state->cmd_argc == ctl->initial_argc) + error (1, 0, _("can not fit single argument within argument list size limit")); + /* option -i (replace_pat) implies -x (exit_if_size_exceeded) */ + if (ctl->replace_pat + || (ctl->exit_if_size_exceeded && + (ctl->lines_per_exec || ctl->args_per_exec))) + error (1, 0, _("argument list too long")); + do_exec (ctl, state); + } + + if (bc_argc_limit_reached(initial_args, ctl, state)) + do_exec (ctl, state); + } + + if (state->cmd_argc >= state->cmd_argv_alloc) + { + if (!state->cmd_argv) + { + state->cmd_argv_alloc = 64; + state->cmd_argv = (char **) xmalloc (sizeof (char *) * state->cmd_argv_alloc); + } + else + { + state->cmd_argv_alloc *= 2; + state->cmd_argv = (char **) xrealloc (state->cmd_argv, + sizeof (char *) * state->cmd_argv_alloc); + } + } + + if (!arg) + state->cmd_argv[state->cmd_argc++] = NULL; + else + { + state->cmd_argv[state->cmd_argc++] = state->argbuf + state->cmd_argv_chars; + if (prefix) + { + strcpy (state->argbuf + state->cmd_argv_chars, prefix); + state->cmd_argv_chars += pfxlen; + } + + strcpy (state->argbuf + state->cmd_argv_chars, arg); + state->cmd_argv_chars += len; + + /* If we have now collected enough arguments, + * do the exec immediately. This must be + * conditional on arg!=NULL, since do_exec() + * actually calls bc_push_arg(ctl, state, NULL, 0, false). + */ + if (bc_argc_limit_reached(initial_args, ctl, state)) + do_exec (ctl, state); + } + + /* If this is an initial argument, set the high-water mark. */ + if (initial_args) + { + state->cmd_initial_argv_chars = state->cmd_argv_chars; + } +} + + +/* Finds the first occurrence of the substring NEEDLE in the string + HAYSTACK. Both strings can be multibyte strings. */ + +static char * +mbstrstr (const char *haystack, const char *needle) +{ +#if DO_MULTIBYTE + if (MB_CUR_MAX > 1) + { + size_t hlen = strlen (haystack); + size_t nlen = strlen (needle); + mbstate_t mbstate; + size_t step; + + memset (&mbstate, 0, sizeof (mbstate_t)); + while (hlen >= nlen) + { + if (memcmp (haystack, needle, nlen) == 0) + return (char *) haystack; + step = mbrlen (haystack, hlen, &mbstate); + if (step <= 0) + break; + haystack += step; + hlen -= step; + } + return NULL; + } +#endif + return strstr (haystack, needle); +} + +static size_t +get_line_max(void) +{ + long val; +#ifdef _SC_LINE_MAX + val = sysconf(_SC_LINE_MAX); +#else + val = -1; +#endif + + if (val > 0) + return val; + + /* either _SC_LINE_MAX was not available or + * there is no particular limit. + */ +#ifdef LINE_MAX + val = LINE_MAX; +#endif + + if (val > 0) + return val; + + return 2048L; /* a reasonable guess. */ +} + + +size_t +bc_get_arg_max(void) +{ + long val; + + /* We may resort to using LONG_MAX, so check it fits. */ + /* XXX: better to do a compile-time check */ + assert( (~(size_t)0) >= LONG_MAX); + +#ifdef _SC_ARG_MAX + val = sysconf(_SC_ARG_MAX); +#else + val = -1; +#endif + + if (val > 0) + return val; + + /* either _SC_ARG_MAX was not available or + * there is no particular limit. + */ +#ifdef ARG_MAX + val = ARG_MAX; +#endif + + if (val > 0) + return val; + + /* The value returned by this function bounds the + * value applied as the ceiling for the -s option. + * Hence it the system won't tell us what its limit + * is, we allow the user to specify more or less + * whatever value they like. + */ + return LONG_MAX; +} + + +static int cb_exec_noop(const struct buildcmd_control *ctl, + struct buildcmd_state *state) +{ + /* does nothing. */ + (void) ctl; + (void) state; + + return 0; +} + + +/* Return how much of ARG_MAX is used by the environment. */ +size_t +bc_size_of_environment (void) +{ + size_t len = 0u; + char **envp = environ; + + while (*envp) + len += strlen (*envp++) + 1; + + return len; +} + + +enum BC_INIT_STATUS +bc_init_controlinfo(struct buildcmd_control *ctl) +{ + size_t size_of_environment = bc_size_of_environment(); + size_t arg_max; + + ctl->posix_arg_size_min = get_line_max(); + arg_max = bc_get_arg_max(); + + /* POSIX.2 requires subtracting 2048. */ + assert(arg_max > 2048u); /* XXX: this is an external condition, should not check it with assert. */ + ctl->posix_arg_size_max = (arg_max - 2048); + + ctl->exit_if_size_exceeded = 0; + + /* Take the size of the environment into account. */ + if (size_of_environment > ctl->posix_arg_size_max) + { + return BC_INIT_ENV_TOO_BIG; + } + else + { + ctl->posix_arg_size_max - size_of_environment; + } + + /* need to subtract 2 on the following line - for Linux/PPC */ + ctl->max_arg_count = (ctl->posix_arg_size_max / sizeof(char*)) - 2u; + assert(ctl->max_arg_count > 0); + ctl->rplen = 0u; + ctl->replace_pat = NULL; + ctl->initial_argc = 0; + ctl->exec_callback = cb_exec_noop; + ctl->lines_per_exec = 0; + ctl->args_per_exec = 0; + + /* Set the initial value of arg_max to the largest value we can + * tolerate. + */ + ctl->arg_max = ctl->posix_arg_size_max; + + return BC_INIT_OK; +} + +void +bc_use_sensible_arg_max(struct buildcmd_control *ctl) +{ + size_t env_size = bc_size_of_environment(); + const size_t arg_size = (128u * 1024u) + env_size; + + /* Check against the upper and lower limits. */ + if (arg_size > ctl->posix_arg_size_max) + ctl->arg_max = ctl->posix_arg_size_max - env_size; + else if (arg_size < ctl->posix_arg_size_min) + ctl->arg_max = ctl->posix_arg_size_min; + else + ctl->arg_max = arg_size; +} + + + + +void +bc_init_state(const struct buildcmd_control *ctl, + struct buildcmd_state *state, + void *context) +{ + state->cmd_argc = 0; + state->cmd_argv_chars = 0; + state->cmd_argv = NULL; + state->cmd_argv_alloc = 0; + + /* XXX: the following memory allocation is inadvisable on systems + * with no ARG_MAX, because ctl->arg_max may actually be close to + * LONG_MAX. Adding one to it is safe though because earlier we + * subtracted 2048. + */ + assert(ctl->arg_max <= (LONG_MAX - 2048L)); + state->argbuf = (char *) xmalloc (ctl->arg_max + 1u); + + state->cmd_argv_chars = state->cmd_initial_argv_chars = 0; + state->todo = 0; + state->usercontext = context; +} + +void +bc_clear_args(const struct buildcmd_control *ctl, + struct buildcmd_state *state) +{ + state->cmd_argc = ctl->initial_argc; + state->cmd_argv_chars = state->cmd_initial_argv_chars; + state->todo = 0; +} + diff --git a/src/bin/findutils/lib/buildcmd.h b/src/bin/findutils/lib/buildcmd.h new file mode 100644 index 0000000000..73e8caa139 --- /dev/null +++ b/src/bin/findutils/lib/buildcmd.h @@ -0,0 +1,129 @@ +/* buildcmd.h -- build command lines from a stream of arguments + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +/* + * Written by James Youngman. + */ +#ifndef INC_BUILDCMD_H +#define INC_BUILDCMD_H 1 + +struct buildcmd_state +{ + /* Number of valid elements in `cmd_argv'. */ + int cmd_argc; /* 0 */ + + /* The list of args being built. */ + char **cmd_argv; /* NULL */ + + /* Number of elements allocated for `cmd_argv'. */ + int cmd_argv_alloc; + + /* Storage for elements of `cmd_argv'. */ + char *argbuf; + + /* Number of chars being used in `cmd_argv'. */ + size_t cmd_argv_chars; + + /* Number of chars being used in `cmd_argv' for the initial args.. */ + size_t cmd_initial_argv_chars; + + /* User context information. */ + void *usercontext; + + /* to-do flag. */ + int todo; +}; + +struct buildcmd_control +{ + /* If true, exit if lines_per_exec or args_per_exec is exceeded. */ + int exit_if_size_exceeded; /* false */ + + /* POSIX limits on the argument length. */ + size_t posix_arg_size_max; + size_t posix_arg_size_min; + + /* The maximum number of characters that can be used per command line. */ + size_t arg_max; + + /* max_arg_count: the maximum number of arguments that can be used. + * + * Many systems include the size of the pointers in ARG_MAX. + * Linux on PPC fails if we just subtract 1 here. + * + * However, not all systems define ARG_MAX. Our bc_get_arg_max() + * function returns a useful value even if ARG_MAX is not defined. + * However, sometimes, max_arg_count is LONG_MAX! + */ + long max_arg_count; + + + /* The length of `replace_pat'. */ + size_t rplen; + + /* If nonzero, then instead of putting the args from stdin at + the end of the command argument list, they are each stuck into the + initial args, replacing each occurrence of the `replace_pat' in the + initial args. */ + char *replace_pat; + + /* Number of initial arguments given on the command line. */ + int initial_argc; /* 0 */ + + /* exec callback. */ + int (*exec_callback)(const struct buildcmd_control *, struct buildcmd_state *); + + /* If nonzero, the maximum number of nonblank lines from stdin to use + per command line. */ + long lines_per_exec; /* 0 */ + + /* The maximum number of arguments to use per command line. */ + long args_per_exec; +}; + +enum BC_INIT_STATUS + { + BC_INIT_OK = 0, + BC_INIT_ENV_TOO_BIG + }; + +extern size_t bc_size_of_environment (void); + + +extern void bc_do_insert (const struct buildcmd_control *ctl, + struct buildcmd_state *state, + char *arg, size_t arglen, + const char *prefix, size_t pfxlen, + const char *linebuf, size_t lblen, + int initial_args); + +extern void bc_push_arg (const struct buildcmd_control *ctl, + struct buildcmd_state *state, + const char *arg, size_t len, + const char *prefix, size_t pfxlen, + int initial_args); + +extern void bc_init_state(const struct buildcmd_control *ctl, + struct buildcmd_state *state, + void *usercontext); +extern enum BC_INIT_STATUS bc_init_controlinfo(struct buildcmd_control *ctl); +extern size_t bc_get_arg_max(void); +extern void bc_use_sensible_arg_max(struct buildcmd_control *ctl); +extern void bc_clear_args(const struct buildcmd_control *ctl, + struct buildcmd_state *state); + + +#endif diff --git a/src/bin/findutils/lib/dirname.c b/src/bin/findutils/lib/dirname.c deleted file mode 100644 index 15d25967af..0000000000 --- a/src/bin/findutils/lib/dirname.c +++ /dev/null @@ -1,70 +0,0 @@ -/* dirname.c -- return all but the last element in a path - Copyright (C) 1990 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#ifdef STDC_HEADERS -#include -#else -char *malloc (); -#endif -#if defined(STDC_HEADERS) || defined(HAVE_STRING_H) -#include -#else -#include -#ifndef strrchr -#define strrchr rindex -#endif -#endif - -/* Return the leading directories part of PATH, - allocated with malloc. If out of memory, return 0. - Assumes that trailing slashes have already been - removed. */ - -char * -dirname (path) - char *path; -{ - char *newpath; - char *slash; - int length; /* Length of result, not including NUL. */ - - slash = strrchr (path, '/'); - if (slash == 0) - { - /* File is in the current directory. */ - path = "."; - length = 1; - } - else - { - /* Remove any trailing slashes from the result. */ - while (slash > path && *slash == '/') - --slash; - - length = slash - path + 1; - } - newpath = (char *) malloc (length + 1); - if (newpath == 0) - return 0; - strncpy (newpath, path, length); - newpath[length] = 0; - return newpath; -} diff --git a/src/bin/findutils/lib/error.c b/src/bin/findutils/lib/error.c deleted file mode 100644 index 19c2ba8863..0000000000 --- a/src/bin/findutils/lib/error.c +++ /dev/null @@ -1,119 +0,0 @@ -/* error.c -- error handler for noninteractive utilities - Copyright (C) 1990, 91, 92, 93, 94 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -/* Written by David MacKenzie . */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include - -#if HAVE_VPRINTF || HAVE_DOPRNT -# if __STDC__ -# include -# define VA_START(args, lastarg) va_start(args, lastarg) -# else -# include -# define VA_START(args, lastarg) va_start(args) -# endif -#else -# define va_alist a1, a2, a3, a4, a5, a6, a7, a8 -# define va_dcl char *a1, *a2, *a3, *a4, *a5, *a6, *a7, *a8; -#endif - -#if STDC_HEADERS -# include -# include -#else -void exit (); -#endif - -/* If NULL, error will flush stdout, then print on stderr the program - name, a colon and a space. Otherwise, error will call this - function without parameters instead. */ -void (*error_print_progname) () = NULL; - -/* The calling program should define program_name and set it to the - name of the executing program. */ -extern char *program_name; - -#if HAVE_STRERROR -char *strerror (); -#else -static char * -private_strerror (errnum) - int errnum; -{ - extern char *sys_errlist[]; - extern int sys_nerr; - - if (errnum > 0 && errnum <= sys_nerr) - return sys_errlist[errnum]; - return "Unknown system error"; -} -#define strerror private_strerror -#endif - -/* Print the program name and error message MESSAGE, which is a printf-style - format string with optional args. - If ERRNUM is nonzero, print its corresponding system error message. - Exit with status STATUS if it is nonzero. */ -/* VARARGS */ - -void -#if defined(VA_START) && __STDC__ -error (int status, int errnum, const char *message, ...) -#else -error (status, errnum, message, va_alist) - int status; - int errnum; - char *message; - va_dcl -#endif -{ -#ifdef VA_START - va_list args; -#endif - - if (error_print_progname) - (*error_print_progname) (); - else - { - fflush (stdout); - fprintf (stderr, "%s: ", program_name); - } - -#ifdef VA_START - VA_START (args, message); -# if HAVE_VPRINTF - vfprintf (stderr, message, args); -# else - _doprnt (message, args, stderr); -# endif - va_end (args); -#else - fprintf (stderr, message, a1, a2, a3, a4, a5, a6, a7, a8); -#endif - - if (errnum) - fprintf (stderr, ": %s", strerror (errnum)); - putc ('\n', stderr); - fflush (stderr); - if (status) - exit (status); -} diff --git a/src/bin/findutils/lib/extendbuf.c b/src/bin/findutils/lib/extendbuf.c new file mode 100644 index 0000000000..0a649f32d9 --- /dev/null +++ b/src/bin/findutils/lib/extendbuf.c @@ -0,0 +1,104 @@ +/* extendbuf.c -- manage a dynamically-allocated buffer + + Copyright 2004, 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +/* Written by James Yougnman . */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include + +#include "xalloc.h" +#include "extendbuf.h" + + +/* We initially use a small default size to ensure that this code + * gets exercised. + */ +#ifndef SIZE_DEFAULT +# define SIZE_DEFAULT 16 +#endif + +static size_t +decide_size(size_t current, size_t wanted) +{ + size_t newsize; + + if (0 == current) + newsize = SIZE_DEFAULT; + else + newsize = current; + + while (newsize < wanted) + { + if (2 * newsize < newsize) + xalloc_die (); + newsize *= 2; + } + return newsize; +} + + +void * +extendbuf(void* existing, size_t wanted, size_t *allocated) +{ + int saved_errno; + size_t newsize; + void *result; /* leave uninitialised to allow static code checkers to identify bugs */ + + saved_errno = errno; + + assert(wanted > 0u); + newsize = decide_size(*allocated, wanted); + + if ( (*allocated) == 0 ) + { + /* Sanity check: If there is no existing allocation size, there + * must be no existing allocated buffer. + */ + assert(NULL == existing); + + (*allocated) = newsize; + result = xmalloc(newsize); + } + else + { + if (newsize != (*allocated) ) + { + (*allocated) = newsize; + result = xrealloc (existing, newsize); + + } + else + { + result = existing; + } + } + + if (result) + { + /* xmalloc() or xrealloc() may have changed errno, but in the + success case we want to preserve the previous value. + */ + errno = saved_errno; + } + return result; +} diff --git a/src/bin/findutils/lib/extendbuf.h b/src/bin/findutils/lib/extendbuf.h new file mode 100644 index 0000000000..6a4e929a39 --- /dev/null +++ b/src/bin/findutils/lib/extendbuf.h @@ -0,0 +1,25 @@ +/* extendbuf.h -- Manage a dynamically-alloicated buffer + + Copyright (C) 2004 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef INC_EXTENDBUF_H +#define INC_EXTENDBUF_H 1 + +void *extendbuf(void* existing, size_t wanted, size_t *allocated); + + +#endif diff --git a/src/bin/findutils/lib/filemode.c b/src/bin/findutils/lib/filemode.c deleted file mode 100644 index c86ee2ff52..0000000000 --- a/src/bin/findutils/lib/filemode.c +++ /dev/null @@ -1,237 +0,0 @@ -/* filemode.c -- make a string describing file modes - Copyright (C) 1985, 1990, 1993 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include -#include - -#ifndef S_IREAD -#define S_IREAD S_IRUSR -#define S_IWRITE S_IWUSR -#define S_IEXEC S_IXUSR -#endif - -#ifdef STAT_MACROS_BROKEN -#undef S_ISBLK -#undef S_ISCHR -#undef S_ISDIR -#undef S_ISFIFO -#undef S_ISLNK -#undef S_ISMPB -#undef S_ISMPC -#undef S_ISNWK -#undef S_ISREG -#undef S_ISSOCK -#endif /* STAT_MACROS_BROKEN. */ - -#if !defined(S_ISBLK) && defined(S_IFBLK) -#define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK) -#endif -#if !defined(S_ISCHR) && defined(S_IFCHR) -#define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR) -#endif -#if !defined(S_ISDIR) && defined(S_IFDIR) -#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) -#endif -#if !defined(S_ISREG) && defined(S_IFREG) -#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) -#endif -#if !defined(S_ISFIFO) && defined(S_IFIFO) -#define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO) -#endif -#if !defined(S_ISLNK) && defined(S_IFLNK) -#define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK) -#endif -#if !defined(S_ISSOCK) && defined(S_IFSOCK) -#define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK) -#endif -#if !defined(S_ISMPB) && defined(S_IFMPB) /* V7 */ -#define S_ISMPB(m) (((m) & S_IFMT) == S_IFMPB) -#define S_ISMPC(m) (((m) & S_IFMT) == S_IFMPC) -#endif -#if !defined(S_ISNWK) && defined(S_IFNWK) /* HP/UX */ -#define S_ISNWK(m) (((m) & S_IFMT) == S_IFNWK) -#endif - -void mode_string (); -static char ftypelet (); -static void rwx (); -static void setst (); - -/* filemodestring - fill in string STR with an ls-style ASCII - representation of the st_mode field of file stats block STATP. - 10 characters are stored in STR; no terminating null is added. - The characters stored in STR are: - - 0 File type. 'd' for directory, 'c' for character - special, 'b' for block special, 'm' for multiplex, - 'l' for symbolic link, 's' for socket, 'p' for fifo, - '-' for regular, '?' for any other file type - - 1 'r' if the owner may read, '-' otherwise. - - 2 'w' if the owner may write, '-' otherwise. - - 3 'x' if the owner may execute, 's' if the file is - set-user-id, '-' otherwise. - 'S' if the file is set-user-id, but the execute - bit isn't set. - - 4 'r' if group members may read, '-' otherwise. - - 5 'w' if group members may write, '-' otherwise. - - 6 'x' if group members may execute, 's' if the file is - set-group-id, '-' otherwise. - 'S' if it is set-group-id but not executable. - - 7 'r' if any user may read, '-' otherwise. - - 8 'w' if any user may write, '-' otherwise. - - 9 'x' if any user may execute, 't' if the file is "sticky" - (will be retained in swap space after execution), '-' - otherwise. - 'T' if the file is sticky but not executable. */ - -void -filemodestring (statp, str) - struct stat *statp; - char *str; -{ - mode_string (statp->st_mode, str); -} - -/* Like filemodestring, but only the relevant part of the `struct stat' - is given as an argument. */ - -void -mode_string (mode, str) - unsigned short mode; - char *str; -{ - str[0] = ftypelet ((long) mode); - rwx ((mode & 0700) << 0, &str[1]); - rwx ((mode & 0070) << 3, &str[4]); - rwx ((mode & 0007) << 6, &str[7]); - setst (mode, str); -} - -/* Return a character indicating the type of file described by - file mode BITS: - 'd' for directories - 'b' for block special files - 'c' for character special files - 'm' for multiplexor files - 'l' for symbolic links - 's' for sockets - 'p' for fifos - '-' for regular files - '?' for any other file type. */ - -static char -ftypelet (bits) - long bits; -{ -#ifdef S_ISBLK - if (S_ISBLK (bits)) - return 'b'; -#endif - if (S_ISCHR (bits)) - return 'c'; - if (S_ISDIR (bits)) - return 'd'; - if (S_ISREG (bits)) - return '-'; -#ifdef S_ISFIFO - if (S_ISFIFO (bits)) - return 'p'; -#endif -#ifdef S_ISLNK - if (S_ISLNK (bits)) - return 'l'; -#endif -#ifdef S_ISSOCK - if (S_ISSOCK (bits)) - return 's'; -#endif -#ifdef S_ISMPC - if (S_ISMPC (bits)) - return 'm'; -#endif -#ifdef S_ISNWK - if (S_ISNWK (bits)) - return 'n'; -#endif - return '?'; -} - -/* Look at read, write, and execute bits in BITS and set - flags in CHARS accordingly. */ - -static void -rwx (bits, chars) - unsigned short bits; - char *chars; -{ - chars[0] = (bits & S_IREAD) ? 'r' : '-'; - chars[1] = (bits & S_IWRITE) ? 'w' : '-'; - chars[2] = (bits & S_IEXEC) ? 'x' : '-'; -} - -/* Set the 's' and 't' flags in file attributes string CHARS, - according to the file mode BITS. */ - -static void -setst (bits, chars) - unsigned short bits; - char *chars; -{ -#ifdef S_ISUID - if (bits & S_ISUID) - { - if (chars[3] != 'x') - /* Set-uid, but not executable by owner. */ - chars[3] = 'S'; - else - chars[3] = 's'; - } -#endif -#ifdef S_ISGID - if (bits & S_ISGID) - { - if (chars[6] != 'x') - /* Set-gid, but not executable by group. */ - chars[6] = 'S'; - else - chars[6] = 's'; - } -#endif -#ifdef S_ISVTX - if (bits & S_ISVTX) - { - if (chars[9] != 'x') - /* Sticky, but not executable by others. */ - chars[9] = 'T'; - else - chars[9] = 't'; - } -#endif -} diff --git a/src/bin/findutils/lib/fnmatch.c b/src/bin/findutils/lib/fnmatch.c deleted file mode 100644 index 2fb65b5216..0000000000 --- a/src/bin/findutils/lib/fnmatch.c +++ /dev/null @@ -1,200 +0,0 @@ -/* Copyright (C) 1991, 1992, 1993 Free Software Foundation, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Library General Public License as -published by the Free Software Foundation; either version 2 of the -License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Library General Public License for more details. - -You should have received a copy of the GNU Library General Public -License along with this library; see the file COPYING.LIB. If -not, write to the Free Software Foundation, Inc., 675 Mass Ave, -Cambridge, MA 02139, USA. */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include -#include -#include - - -/* Comment out all this code if we are using the GNU C Library, and are not - actually compiling the library itself. This code is part of the GNU C - Library, but also included in many other GNU distributions. Compiling - and linking in this code is a waste when using the GNU C library - (especially if it is a shared library). Rather than having every GNU - program understand `configure --with-gnu-libc' and omit the object files, - it is simpler to just do this in the source for each such file. */ - -#if defined (_LIBC) || !defined (__GNU_LIBRARY__) - - -#if !defined(__GNU_LIBRARY__) && !defined(STDC_HEADERS) -extern int errno; -#endif - -/* Match STRING against the filename pattern PATTERN, returning zero if - it matches, nonzero if not. */ -int -fnmatch (pattern, string, flags) - const char *pattern; - const char *string; - int flags; -{ - register const char *p = pattern, *n = string; - register char c; - -/* Note that this evalutes C many times. */ -#define FOLD(c) ((flags & FNM_CASEFOLD) && isupper (c) ? tolower (c) : (c)) - - while ((c = *p++) != '\0') - { - c = FOLD (c); - - switch (c) - { - case '?': - if (*n == '\0') - return FNM_NOMATCH; - else if ((flags & FNM_FILE_NAME) && *n == '/') - return FNM_NOMATCH; - else if ((flags & FNM_PERIOD) && *n == '.' && - (n == string || ((flags & FNM_FILE_NAME) && n[-1] == '/'))) - return FNM_NOMATCH; - break; - - case '\\': - if (!(flags & FNM_NOESCAPE)) - { - c = *p++; - c = FOLD (c); - } - if (FOLD (*n) != c) - return FNM_NOMATCH; - break; - - case '*': - if ((flags & FNM_PERIOD) && *n == '.' && - (n == string || ((flags & FNM_FILE_NAME) && n[-1] == '/'))) - return FNM_NOMATCH; - - for (c = *p++; c == '?' || c == '*'; c = *p++, ++n) - if (((flags & FNM_FILE_NAME) && *n == '/') || - (c == '?' && *n == '\0')) - return FNM_NOMATCH; - - if (c == '\0') - return 0; - - { - char c1 = (!(flags & FNM_NOESCAPE) && c == '\\') ? *p : c; - c1 = FOLD (c1); - for (--p; *n != '\0'; ++n) - if ((c == '[' || FOLD (*n) == c1) && - fnmatch (p, n, flags & ~FNM_PERIOD) == 0) - return 0; - return FNM_NOMATCH; - } - - case '[': - { - /* Nonzero if the sense of the character class is inverted. */ - register int not; - - if (*n == '\0') - return FNM_NOMATCH; - - if ((flags & FNM_PERIOD) && *n == '.' && - (n == string || ((flags & FNM_FILE_NAME) && n[-1] == '/'))) - return FNM_NOMATCH; - - not = (*p == '!' || *p == '^'); - if (not) - ++p; - - c = *p++; - for (;;) - { - register char cstart = c, cend = c; - - if (!(flags & FNM_NOESCAPE) && c == '\\') - cstart = cend = *p++; - - cstart = cend = FOLD (cstart); - - if (c == '\0') - /* [ (unterminated) loses. */ - return FNM_NOMATCH; - - c = *p++; - c = FOLD (c); - - if ((flags & FNM_FILE_NAME) && c == '/') - /* [/] can never match. */ - return FNM_NOMATCH; - - if (c == '-' && *p != ']') - { - cend = *p++; - if (!(flags & FNM_NOESCAPE) && cend == '\\') - cend = *p++; - if (cend == '\0') - return FNM_NOMATCH; - cend = FOLD (cend); - - c = *p++; - } - - if (FOLD (*n) >= cstart && FOLD (*n) <= cend) - goto matched; - - if (c == ']') - break; - } - if (!not) - return FNM_NOMATCH; - break; - - matched:; - /* Skip the rest of the [...] that already matched. */ - while (c != ']') - { - if (c == '\0') - /* [... (unterminated) loses. */ - return FNM_NOMATCH; - - c = *p++; - if (!(flags & FNM_NOESCAPE) && c == '\\') - /* XXX 1003.2d11 is unclear if this is right. */ - ++p; - } - if (not) - return FNM_NOMATCH; - } - break; - - default: - if (c != FOLD (*n)) - return FNM_NOMATCH; - } - - ++n; - } - - if (*n == '\0') - return 0; - - if ((flags & FNM_LEADING_DIR) && *n == '/') - /* The FNM_LEADING_DIR flag says that "foo*" matches "foobar/frobozz". */ - return 0; - - return FNM_NOMATCH; -} - -#endif /* _LIBC or not __GNU_LIBRARY__. */ diff --git a/src/bin/findutils/lib/fnmatch.h b/src/bin/findutils/lib/fnmatch.h deleted file mode 100644 index 69eab0c0d6..0000000000 --- a/src/bin/findutils/lib/fnmatch.h +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright (C) 1991, 1992, 1993 Free Software Foundation, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Library General Public License as -published by the Free Software Foundation; either version 2 of the -License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Library General Public License for more details. - -You should have received a copy of the GNU Library General Public -License along with this library; see the file COPYING.LIB. If -not, write to the Free Software Foundation, Inc., 675 Mass Ave, -Cambridge, MA 02139, USA. */ - -#ifndef _FNMATCH_H - -#define _FNMATCH_H 1 - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined (__cplusplus) || (defined (__STDC__) && __STDC__) -#undef __P -#define __P(args) args -#else /* Not C++ or ANSI C. */ -#undef __P -#define __P(args) () -/* We can get away without defining `const' here only because in this file - it is used only inside the prototype for `fnmatch', which is elided in - non-ANSI C where `const' is problematical. */ -#endif /* C++ or ANSI C. */ - - -/* We #undef these before defining them because some losing systems - (HP-UX A.08.07 for example) define these in . */ -#undef FNM_PATHNAME -#undef FNM_NOESCAPE -#undef FNM_PERIOD - -/* Bits set in the FLAGS argument to `fnmatch'. */ -#define FNM_PATHNAME (1 << 0) /* No wildcard can ever match `/'. */ -#define FNM_NOESCAPE (1 << 1) /* Backslashes don't quote special chars. */ -#define FNM_PERIOD (1 << 2) /* Leading `.' is matched only explicitly. */ - -#if !defined (_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 2 || defined (_GNU_SOURCE) -#define FNM_FILE_NAME FNM_PATHNAME /* Preferred GNU name. */ -#define FNM_LEADING_DIR (1 << 3) /* Ignore `/...' after a match. */ -#define FNM_CASEFOLD (1 << 4) /* Compare without regard to case. */ -#endif - -/* Value returned by `fnmatch' if STRING does not match PATTERN. */ -#define FNM_NOMATCH 1 - -/* Match STRING against the filename pattern PATTERN, - returning zero if it matches, FNM_NOMATCH if not. */ -extern int fnmatch __P ((const char *__pattern, const char *__string, - int __flags)); - -#ifdef __cplusplus -} -#endif - -#endif /* fnmatch.h */ diff --git a/src/bin/findutils/lib/forcefindlib.c b/src/bin/findutils/lib/forcefindlib.c new file mode 100644 index 0000000000..6acbba8ff6 --- /dev/null +++ b/src/bin/findutils/lib/forcefindlib.c @@ -0,0 +1,49 @@ +/* Ensures that the FINDLIB_REPLACE_FUNCS macro in configure.in works + Copyright (C) 2004, 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +*/ + +/* Written by James Youngman. */ + + +#ifdef HAVE_CONFIG_H +#include +#endif + + +extern void forcefindlib(void); /* prevent GCC warning... */ + + + +/* forcefindlib + * + * This function exists only to be pulled into libfind.a by the + * FINDLIB_REPLACE_FUNCS macro in configure.in. We already have + * AC_REPLACE_FUNCS, but that adds to LIBOBJS, and that's a gnulib thing + * in the case of findutils. Hence we have out own library of replacement + * functions which aren't in gnulib (or aren't in it any more). An example + * of this is waitpid(). I develop on a system that doesn't + * lack waitpid, for example. Therefore FINDLIB_REPLACE_FUNCS(waitpid) + * never puts waitpid.o into FINDLIBOBJS. Hence, to ensure that these + * macros are tested every time, we use FINDLIB_REPLACE_FUNCS on a function + * that never exists anywhere, so always needs to be pulled in. That function + * is forcefindlib(). + */ +void +forcefindlib(void) +{ + /* does nothing, exists only to ensure that FINDLIB_REPLACE_FUNCS works. */ +} diff --git a/src/bin/findutils/lib/getline.c b/src/bin/findutils/lib/getline.c deleted file mode 100644 index 519ff9326b..0000000000 --- a/src/bin/findutils/lib/getline.c +++ /dev/null @@ -1,126 +0,0 @@ -/* getline.c -- Replacement for GNU C library function getline - -Copyright (C) 1993 Free Software Foundation, Inc. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License as -published by the Free Software Foundation; either version 2 of the -License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, but -WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -/* Written by Jan Brittenson, bson@gnu.ai.mit.edu. */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include -#include -#define NDEBUG -#include - -#if STDC_HEADERS -#include -#else -char *malloc (), *realloc (); -#endif - -/* Always add at least this many bytes when extending the buffer. */ -#define MIN_CHUNK 64 - -/* Read up to (and including) a TERMINATOR from STREAM into *LINEPTR - + OFFSET (and null-terminate it). *LINEPTR is a pointer returned from - malloc (or NULL), pointing to *N characters of space. It is realloc'd - as necessary. Return the number of characters read (not including the - null terminator), or -1 on error or EOF. */ - -int -getstr (lineptr, n, stream, terminator, offset) - char **lineptr; - size_t *n; - FILE *stream; - char terminator; - int offset; -{ - int nchars_avail; /* Allocated but unused chars in *LINEPTR. */ - char *read_pos; /* Where we're reading into *LINEPTR. */ - int ret; - - if (!lineptr || !n || !stream) - return -1; - - if (!*lineptr) - { - *n = MIN_CHUNK; - *lineptr = malloc (*n); - if (!*lineptr) - return -1; - } - - nchars_avail = *n - offset; - read_pos = *lineptr + offset; - - for (;;) - { - register int c = getc (stream); - - /* We always want at least one char left in the buffer, since we - always (unless we get an error while reading the first char) - NUL-terminate the line buffer. */ - - assert(*n - nchars_avail == read_pos - *lineptr); - if (nchars_avail < 1) - { - if (*n > MIN_CHUNK) - *n *= 2; - else - *n += MIN_CHUNK; - - nchars_avail = *n + *lineptr - read_pos; - *lineptr = realloc (*lineptr, *n); - if (!*lineptr) - return -1; - read_pos = *n - nchars_avail + *lineptr; - assert(*n - nchars_avail == read_pos - *lineptr); - } - - if (c == EOF || ferror (stream)) - { - /* Return partial line, if any. */ - if (read_pos == *lineptr) - return -1; - else - break; - } - - *read_pos++ = c; - nchars_avail--; - - if (c == terminator) - /* Return the line. */ - break; - } - - /* Done - NUL terminate and return the number of chars read. */ - *read_pos = '\0'; - - ret = read_pos - (*lineptr + offset); - return ret; -} - -int -getline (lineptr, n, stream) - char **lineptr; - size_t *n; - FILE *stream; -{ - return getstr (lineptr, n, stream, '\n', 0); -} diff --git a/src/bin/findutils/lib/getopt.c b/src/bin/findutils/lib/getopt.c deleted file mode 100644 index 43c0a6a986..0000000000 --- a/src/bin/findutils/lib/getopt.c +++ /dev/null @@ -1,748 +0,0 @@ -/* Getopt for GNU. - NOTE: getopt is now part of the C library, so if you don't know what - "Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu - before changing it! - - Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94 - Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by the - Free Software Foundation; either version 2, or (at your option) any - later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ - -/* This tells Alpha OSF/1 not to define a getopt prototype in . - Ditto for AIX 3.2 and . */ -#ifndef _NO_PROTO -#define _NO_PROTO -#endif - -#ifdef HAVE_CONFIG_H -#include -#endif - -#if !defined (__STDC__) || !__STDC__ -/* This is a separate conditional since some stdc systems - reject `defined (const)'. */ -#ifndef const -#define const -#endif -#endif - -#include - -/* Comment out all this code if we are using the GNU C Library, and are not - actually compiling the library itself. This code is part of the GNU C - Library, but also included in many other GNU distributions. Compiling - and linking in this code is a waste when using the GNU C library - (especially if it is a shared library). Rather than having every GNU - program understand `configure --with-gnu-libc' and omit the object files, - it is simpler to just do this in the source for each such file. */ - -#if defined (_LIBC) || !defined (__GNU_LIBRARY__) - - -/* This needs to come after some library #include - to get __GNU_LIBRARY__ defined. */ -#ifdef __GNU_LIBRARY__ -/* Don't include stdlib.h for non-GNU C libraries because some of them - contain conflicting prototypes for getopt. */ -#include -#endif /* GNU C library. */ - -/* This version of `getopt' appears to the caller like standard Unix `getopt' - but it behaves differently for the user, since it allows the user - to intersperse the options with the other arguments. - - As `getopt' works, it permutes the elements of ARGV so that, - when it is done, all the options precede everything else. Thus - all application programs are extended to handle flexible argument order. - - Setting the environment variable POSIXLY_CORRECT disables permutation. - Then the behavior is completely standard. - - GNU application programs can use a third alternative mode in which - they can distinguish the relative order of options and other arguments. */ - -#include "getopt.h" - -/* For communication from `getopt' to the caller. - When `getopt' finds an option that takes an argument, - the argument value is returned here. - Also, when `ordering' is RETURN_IN_ORDER, - each non-option ARGV-element is returned here. */ - -char *optarg = NULL; - -/* Index in ARGV of the next element to be scanned. - This is used for communication to and from the caller - and for communication between successive calls to `getopt'. - - On entry to `getopt', zero means this is the first call; initialize. - - When `getopt' returns EOF, this is the index of the first of the - non-option elements that the caller should itself scan. - - Otherwise, `optind' communicates from one call to the next - how much of ARGV has been scanned so far. */ - -/* XXX 1003.2 says this must be 1 before any call. */ -int optind = 0; - -/* The next char to be scanned in the option-element - in which the last option character we returned was found. - This allows us to pick up the scan where we left off. - - If this is zero, or a null string, it means resume the scan - by advancing to the next ARGV-element. */ - -static char *nextchar; - -/* Callers store zero here to inhibit the error message - for unrecognized options. */ - -int opterr = 1; - -/* Set to an option character which was unrecognized. - This must be initialized on some systems to avoid linking in the - system's own getopt implementation. */ - -int optopt = '?'; - -/* Describe how to deal with options that follow non-option ARGV-elements. - - If the caller did not specify anything, - the default is REQUIRE_ORDER if the environment variable - POSIXLY_CORRECT is defined, PERMUTE otherwise. - - REQUIRE_ORDER means don't recognize them as options; - stop option processing when the first non-option is seen. - This is what Unix does. - This mode of operation is selected by either setting the environment - variable POSIXLY_CORRECT, or using `+' as the first character - of the list of option characters. - - PERMUTE is the default. We permute the contents of ARGV as we scan, - so that eventually all the non-options are at the end. This allows options - to be given in any order, even with programs that were not written to - expect this. - - RETURN_IN_ORDER is an option available to programs that were written - to expect options and other ARGV-elements in any order and that care about - the ordering of the two. We describe each non-option ARGV-element - as if it were the argument of an option with character code 1. - Using `-' as the first character of the list of option characters - selects this mode of operation. - - The special argument `--' forces an end of option-scanning regardless - of the value of `ordering'. In the case of RETURN_IN_ORDER, only - `--' can cause `getopt' to return EOF with `optind' != ARGC. */ - -static enum -{ - REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER -} ordering; - -/* Value of POSIXLY_CORRECT environment variable. */ -static char *posixly_correct; - -#ifdef __GNU_LIBRARY__ -/* We want to avoid inclusion of string.h with non-GNU libraries - because there are many ways it can cause trouble. - On some systems, it contains special magic macros that don't work - in GCC. */ -#include -#define my_index strchr -#else - -/* Avoid depending on library functions or files - whose names are inconsistent. */ - -char *getenv (); - -static char * -my_index (str, chr) - const char *str; - int chr; -{ - while (*str) - { - if (*str == chr) - return (char *) str; - str++; - } - return 0; -} - -/* If using GCC, we can safely declare strlen this way. - If not using GCC, it is ok not to declare it. */ -#ifdef __GNUC__ -/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. - That was relevant to code that was here before. */ -#if !defined (__STDC__) || !__STDC__ -/* gcc with -traditional declares the built-in strlen to return int, - and has done so at least since version 2.4.5. -- rms. */ -extern int strlen (const char *); -#endif /* not __STDC__ */ -#endif /* __GNUC__ */ - -#endif /* not __GNU_LIBRARY__ */ - -/* Handle permutation of arguments. */ - -/* Describe the part of ARGV that contains non-options that have - been skipped. `first_nonopt' is the index in ARGV of the first of them; - `last_nonopt' is the index after the last of them. */ - -static int first_nonopt; -static int last_nonopt; - -/* Exchange two adjacent subsequences of ARGV. - One subsequence is elements [first_nonopt,last_nonopt) - which contains all the non-options that have been skipped so far. - The other is elements [last_nonopt,optind), which contains all - the options processed since those non-options were skipped. - - `first_nonopt' and `last_nonopt' are relocated so that they describe - the new indices of the non-options in ARGV after they are moved. */ - -static void -exchange (argv) - char **argv; -{ - int bottom = first_nonopt; - int middle = last_nonopt; - int top = optind; - char *tem; - - /* Exchange the shorter segment with the far end of the longer segment. - That puts the shorter segment into the right place. - It leaves the longer segment in the right place overall, - but it consists of two parts that need to be swapped next. */ - - while (top > middle && middle > bottom) - { - if (top - middle > middle - bottom) - { - /* Bottom segment is the short one. */ - int len = middle - bottom; - register int i; - - /* Swap it with the top part of the top segment. */ - for (i = 0; i < len; i++) - { - tem = argv[bottom + i]; - argv[bottom + i] = argv[top - (middle - bottom) + i]; - argv[top - (middle - bottom) + i] = tem; - } - /* Exclude the moved bottom segment from further swapping. */ - top -= len; - } - else - { - /* Top segment is the short one. */ - int len = top - middle; - register int i; - - /* Swap it with the bottom part of the bottom segment. */ - for (i = 0; i < len; i++) - { - tem = argv[bottom + i]; - argv[bottom + i] = argv[middle + i]; - argv[middle + i] = tem; - } - /* Exclude the moved top segment from further swapping. */ - bottom += len; - } - } - - /* Update records for the slots the non-options now occupy. */ - - first_nonopt += (optind - last_nonopt); - last_nonopt = optind; -} - -/* Initialize the internal data when the first call is made. */ - -static const char * -_getopt_initialize (optstring) - const char *optstring; -{ - /* Start processing options with ARGV-element 1 (since ARGV-element 0 - is the program name); the sequence of previously skipped - non-option ARGV-elements is empty. */ - - first_nonopt = last_nonopt = optind = 1; - - nextchar = NULL; - - posixly_correct = getenv ("POSIXLY_CORRECT"); - - /* Determine how to handle the ordering of options and nonoptions. */ - - if (optstring[0] == '-') - { - ordering = RETURN_IN_ORDER; - ++optstring; - } - else if (optstring[0] == '+') - { - ordering = REQUIRE_ORDER; - ++optstring; - } - else if (posixly_correct != NULL) - ordering = REQUIRE_ORDER; - else - ordering = PERMUTE; - - return optstring; -} - -/* Scan elements of ARGV (whose length is ARGC) for option characters - given in OPTSTRING. - - If an element of ARGV starts with '-', and is not exactly "-" or "--", - then it is an option element. The characters of this element - (aside from the initial '-') are option characters. If `getopt' - is called repeatedly, it returns successively each of the option characters - from each of the option elements. - - If `getopt' finds another option character, it returns that character, - updating `optind' and `nextchar' so that the next call to `getopt' can - resume the scan with the following option character or ARGV-element. - - If there are no more option characters, `getopt' returns `EOF'. - Then `optind' is the index in ARGV of the first ARGV-element - that is not an option. (The ARGV-elements have been permuted - so that those that are not options now come last.) - - OPTSTRING is a string containing the legitimate option characters. - If an option character is seen that is not listed in OPTSTRING, - return '?' after printing an error message. If you set `opterr' to - zero, the error message is suppressed but we still return '?'. - - If a char in OPTSTRING is followed by a colon, that means it wants an arg, - so the following text in the same ARGV-element, or the text of the following - ARGV-element, is returned in `optarg'. Two colons mean an option that - wants an optional arg; if there is text in the current ARGV-element, - it is returned in `optarg', otherwise `optarg' is set to zero. - - If OPTSTRING starts with `-' or `+', it requests different methods of - handling the non-option ARGV-elements. - See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. - - Long-named options begin with `--' instead of `-'. - Their names may be abbreviated as long as the abbreviation is unique - or is an exact match for some defined option. If they have an - argument, it follows the option name in the same ARGV-element, separated - from the option name by a `=', or else the in next ARGV-element. - When `getopt' finds a long-named option, it returns 0 if that option's - `flag' field is nonzero, the value of the option's `val' field - if the `flag' field is zero. - - The elements of ARGV aren't really const, because we permute them. - But we pretend they're const in the prototype to be compatible - with other systems. - - LONGOPTS is a vector of `struct option' terminated by an - element containing a name which is zero. - - LONGIND returns the index in LONGOPT of the long-named option found. - It is only valid when a long-named option has been found by the most - recent call. - - If LONG_ONLY is nonzero, '-' as well as '--' can introduce - long-named options. */ - -int -_getopt_internal (argc, argv, optstring, longopts, longind, long_only) - int argc; - char *const *argv; - const char *optstring; - const struct option *longopts; - int *longind; - int long_only; -{ - optarg = NULL; - - if (optind == 0) - optstring = _getopt_initialize (optstring); - - if (nextchar == NULL || *nextchar == '\0') - { - /* Advance to the next ARGV-element. */ - - if (ordering == PERMUTE) - { - /* If we have just processed some options following some non-options, - exchange them so that the options come first. */ - - if (first_nonopt != last_nonopt && last_nonopt != optind) - exchange ((char **) argv); - else if (last_nonopt != optind) - first_nonopt = optind; - - /* Skip any additional non-options - and extend the range of non-options previously skipped. */ - - while (optind < argc - && (argv[optind][0] != '-' || argv[optind][1] == '\0')) - optind++; - last_nonopt = optind; - } - - /* The special ARGV-element `--' means premature end of options. - Skip it like a null option, - then exchange with previous non-options as if it were an option, - then skip everything else like a non-option. */ - - if (optind != argc && !strcmp (argv[optind], "--")) - { - optind++; - - if (first_nonopt != last_nonopt && last_nonopt != optind) - exchange ((char **) argv); - else if (first_nonopt == last_nonopt) - first_nonopt = optind; - last_nonopt = argc; - - optind = argc; - } - - /* If we have done all the ARGV-elements, stop the scan - and back over any non-options that we skipped and permuted. */ - - if (optind == argc) - { - /* Set the next-arg-index to point at the non-options - that we previously skipped, so the caller will digest them. */ - if (first_nonopt != last_nonopt) - optind = first_nonopt; - return EOF; - } - - /* If we have come to a non-option and did not permute it, - either stop the scan or describe it to the caller and pass it by. */ - - if ((argv[optind][0] != '-' || argv[optind][1] == '\0')) - { - if (ordering == REQUIRE_ORDER) - return EOF; - optarg = argv[optind++]; - return 1; - } - - /* We have found another option-ARGV-element. - Skip the initial punctuation. */ - - nextchar = (argv[optind] + 1 - + (longopts != NULL && argv[optind][1] == '-')); - } - - /* Decode the current option-ARGV-element. */ - - /* Check whether the ARGV-element is a long option. - - If long_only and the ARGV-element has the form "-f", where f is - a valid short option, don't consider it an abbreviated form of - a long option that starts with f. Otherwise there would be no - way to give the -f short option. - - On the other hand, if there's a long option "fubar" and - the ARGV-element is "-fu", do consider that an abbreviation of - the long option, just like "--fu", and not "-f" with arg "u". - - This distinction seems to be the most useful approach. */ - - if (longopts != NULL - && (argv[optind][1] == '-' - || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1]))))) - { - char *nameend; - const struct option *p; - const struct option *pfound = NULL; - int exact = 0; - int ambig = 0; - int indfound; - int option_index; - - for (nameend = nextchar; *nameend && *nameend != '='; nameend++) - /* Do nothing. */ ; - - /* Test all long options for either exact match - or abbreviated matches. */ - for (p = longopts, option_index = 0; p->name; p++, option_index++) - if (!strncmp (p->name, nextchar, nameend - nextchar)) - { - if (nameend - nextchar == strlen (p->name)) - { - /* Exact match found. */ - pfound = p; - indfound = option_index; - exact = 1; - break; - } - else if (pfound == NULL) - { - /* First nonexact match found. */ - pfound = p; - indfound = option_index; - } - else - /* Second or later nonexact match found. */ - ambig = 1; - } - - if (ambig && !exact) - { - if (opterr) - fprintf (stderr, "%s: option `%s' is ambiguous\n", - argv[0], argv[optind]); - nextchar += strlen (nextchar); - optind++; - return '?'; - } - - if (pfound != NULL) - { - option_index = indfound; - optind++; - if (*nameend) - { - /* Don't test has_arg with >, because some C compilers don't - allow it to be used on enums. */ - if (pfound->has_arg) - optarg = nameend + 1; - else - { - if (opterr) - { - if (argv[optind - 1][1] == '-') - /* --option */ - fprintf (stderr, - "%s: option `--%s' doesn't allow an argument\n", - argv[0], pfound->name); - else - /* +option or -option */ - fprintf (stderr, - "%s: option `%c%s' doesn't allow an argument\n", - argv[0], argv[optind - 1][0], pfound->name); - } - nextchar += strlen (nextchar); - return '?'; - } - } - else if (pfound->has_arg == 1) - { - if (optind < argc) - optarg = argv[optind++]; - else - { - if (opterr) - fprintf (stderr, "%s: option `%s' requires an argument\n", - argv[0], argv[optind - 1]); - nextchar += strlen (nextchar); - return optstring[0] == ':' ? ':' : '?'; - } - } - nextchar += strlen (nextchar); - if (longind != NULL) - *longind = option_index; - if (pfound->flag) - { - *(pfound->flag) = pfound->val; - return 0; - } - return pfound->val; - } - - /* Can't find it as a long option. If this is not getopt_long_only, - or the option starts with '--' or is not a valid short - option, then it's an error. - Otherwise interpret it as a short option. */ - if (!long_only || argv[optind][1] == '-' - || my_index (optstring, *nextchar) == NULL) - { - if (opterr) - { - if (argv[optind][1] == '-') - /* --option */ - fprintf (stderr, "%s: unrecognized option `--%s'\n", - argv[0], nextchar); - else - /* +option or -option */ - fprintf (stderr, "%s: unrecognized option `%c%s'\n", - argv[0], argv[optind][0], nextchar); - } - nextchar = (char *) ""; - optind++; - return '?'; - } - } - - /* Look at and handle the next short option-character. */ - - { - char c = *nextchar++; - char *temp = my_index (optstring, c); - - /* Increment `optind' when we start to process its last character. */ - if (*nextchar == '\0') - ++optind; - - if (temp == NULL || c == ':') - { - if (opterr) - { - if (posixly_correct) - /* 1003.2 specifies the format of this message. */ - fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c); - else - fprintf (stderr, "%s: invalid option -- %c\n", argv[0], c); - } - optopt = c; - return '?'; - } - if (temp[1] == ':') - { - if (temp[2] == ':') - { - /* This is an option that accepts an argument optionally. */ - if (*nextchar != '\0') - { - optarg = nextchar; - optind++; - } - else - optarg = NULL; - nextchar = NULL; - } - else - { - /* This is an option that requires an argument. */ - if (*nextchar != '\0') - { - optarg = nextchar; - /* If we end this ARGV-element by taking the rest as an arg, - we must advance to the next element now. */ - optind++; - } - else if (optind == argc) - { - if (opterr) - { - /* 1003.2 specifies the format of this message. */ - fprintf (stderr, "%s: option requires an argument -- %c\n", - argv[0], c); - } - optopt = c; - if (optstring[0] == ':') - c = ':'; - else - c = '?'; - } - else - /* We already incremented `optind' once; - increment it again when taking next ARGV-elt as argument. */ - optarg = argv[optind++]; - nextchar = NULL; - } - } - return c; - } -} - -int -getopt (argc, argv, optstring) - int argc; - char *const *argv; - const char *optstring; -{ - return _getopt_internal (argc, argv, optstring, - (const struct option *) 0, - (int *) 0, - 0); -} - -#endif /* _LIBC or not __GNU_LIBRARY__. */ - -#ifdef TEST - -/* Compile with -DTEST to make an executable for use in testing - the above definition of `getopt'. */ - -int -main (argc, argv) - int argc; - char **argv; -{ - int c; - int digit_optind = 0; - - while (1) - { - int this_option_optind = optind ? optind : 1; - - c = getopt (argc, argv, "abc:d:0123456789"); - if (c == EOF) - break; - - switch (c) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - if (digit_optind != 0 && digit_optind != this_option_optind) - printf ("digits occur in two different argv-elements.\n"); - digit_optind = this_option_optind; - printf ("option %c\n", c); - break; - - case 'a': - printf ("option a\n"); - break; - - case 'b': - printf ("option b\n"); - break; - - case 'c': - printf ("option c with value `%s'\n", optarg); - break; - - case '?': - break; - - default: - printf ("?? getopt returned character code 0%o ??\n", c); - } - } - - if (optind < argc) - { - printf ("non-option ARGV-elements: "); - while (optind < argc) - printf ("%s ", argv[optind++]); - printf ("\n"); - } - - exit (0); -} - -#endif /* TEST */ diff --git a/src/bin/findutils/lib/getopt.h b/src/bin/findutils/lib/getopt.h deleted file mode 100644 index 4ac33b7182..0000000000 --- a/src/bin/findutils/lib/getopt.h +++ /dev/null @@ -1,129 +0,0 @@ -/* Declarations for getopt. - Copyright (C) 1989, 90, 91, 92, 93, 94 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by the - Free Software Foundation; either version 2, or (at your option) any - later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ - -#ifndef _GETOPT_H -#define _GETOPT_H 1 - -#ifdef __cplusplus -extern "C" { -#endif - -/* For communication from `getopt' to the caller. - When `getopt' finds an option that takes an argument, - the argument value is returned here. - Also, when `ordering' is RETURN_IN_ORDER, - each non-option ARGV-element is returned here. */ - -extern char *optarg; - -/* Index in ARGV of the next element to be scanned. - This is used for communication to and from the caller - and for communication between successive calls to `getopt'. - - On entry to `getopt', zero means this is the first call; initialize. - - When `getopt' returns EOF, this is the index of the first of the - non-option elements that the caller should itself scan. - - Otherwise, `optind' communicates from one call to the next - how much of ARGV has been scanned so far. */ - -extern int optind; - -/* Callers store zero here to inhibit the error message `getopt' prints - for unrecognized options. */ - -extern int opterr; - -/* Set to an option character which was unrecognized. */ - -extern int optopt; - -/* Describe the long-named options requested by the application. - The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector - of `struct option' terminated by an element containing a name which is - zero. - - The field `has_arg' is: - no_argument (or 0) if the option does not take an argument, - required_argument (or 1) if the option requires an argument, - optional_argument (or 2) if the option takes an optional argument. - - If the field `flag' is not NULL, it points to a variable that is set - to the value given in the field `val' when the option is found, but - left unchanged if the option is not found. - - To have a long-named option do something other than set an `int' to - a compiled-in constant, such as set a value from `optarg', set the - option's `flag' field to zero and its `val' field to a nonzero - value (the equivalent single-letter option character, if there is - one). For long options that have a zero `flag' field, `getopt' - returns the contents of the `val' field. */ - -struct option -{ -#if defined (__STDC__) && __STDC__ - const char *name; -#else - char *name; -#endif - /* has_arg can't be an enum because some compilers complain about - type mismatches in all the code that assumes it is an int. */ - int has_arg; - int *flag; - int val; -}; - -/* Names for the values of the `has_arg' field of `struct option'. */ - -#define no_argument 0 -#define required_argument 1 -#define optional_argument 2 - -#if defined (__STDC__) && __STDC__ -#ifdef __GNU_LIBRARY__ -/* Many other libraries have conflicting prototypes for getopt, with - differences in the consts, in stdlib.h. To avoid compilation - errors, only prototype getopt for the GNU C library. */ -extern int getopt (int argc, char *const *argv, const char *shortopts); -#else /* not __GNU_LIBRARY__ */ -extern int getopt (); -#endif /* __GNU_LIBRARY__ */ -extern int getopt_long (int argc, char *const *argv, const char *shortopts, - const struct option *longopts, int *longind); -extern int getopt_long_only (int argc, char *const *argv, - const char *shortopts, - const struct option *longopts, int *longind); - -/* Internal only. Users should not call this directly. */ -extern int _getopt_internal (int argc, char *const *argv, - const char *shortopts, - const struct option *longopts, int *longind, - int long_only); -#else /* not __STDC__ */ -extern int getopt (); -extern int getopt_long (); -extern int getopt_long_only (); - -extern int _getopt_internal (); -#endif /* __STDC__ */ - -#ifdef __cplusplus -} -#endif - -#endif /* _GETOPT_H */ diff --git a/src/bin/findutils/lib/gnulib-version.c b/src/bin/findutils/lib/gnulib-version.c new file mode 100644 index 0000000000..db4114c8ab --- /dev/null +++ b/src/bin/findutils/lib/gnulib-version.c @@ -0,0 +1,2 @@ +/* This file is automatically generated by import-gnulib.sh and simply records which version of gnulib we used. */ +const char * const gnulib_version = "8e128ebf42e16c8631f971a68f188c30962818be"; diff --git a/src/bin/findutils/lib/gnulib-version.h b/src/bin/findutils/lib/gnulib-version.h new file mode 100644 index 0000000000..1c841b0ca5 --- /dev/null +++ b/src/bin/findutils/lib/gnulib-version.h @@ -0,0 +1,19 @@ +/* gnulib-version.h + Copyright (C) 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +extern const char * const gnulib_version; + diff --git a/src/bin/findutils/lib/idcache.c b/src/bin/findutils/lib/idcache.c deleted file mode 100644 index 34dcc07c56..0000000000 --- a/src/bin/findutils/lib/idcache.c +++ /dev/null @@ -1,210 +0,0 @@ -/* idcache.c -- map user and group IDs, cached for speed - Copyright (C) 1985, 1988, 1989, 1990 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include -#include -#include -#include - -#if defined(STDC_HEADERS) || defined(HAVE_STRING_H) -#include -#else -#include -#endif - -#ifdef HAVE_UNISTD_H -#include -#endif -#ifndef _POSIX_VERSION -struct passwd *getpwuid (); -struct passwd *getpwnam (); -struct group *getgrgid (); -struct group *getgrnam (); -#endif - -char *xmalloc (); -char *xstrdup (); - -struct userid -{ - union - { - uid_t u; - gid_t g; - } id; - char *name; - struct userid *next; -}; - -static struct userid *user_alist; - -/* The members of this list have names not in the local passwd file. */ -static struct userid *nouser_alist; - -/* Translate UID to a login name or a stringified number, - with cache. */ - -char * -getuser (uid) - uid_t uid; -{ - register struct userid *tail; - struct passwd *pwent; - char usernum_string[20]; - - for (tail = user_alist; tail; tail = tail->next) - if (tail->id.u == uid) - return tail->name; - - pwent = getpwuid (uid); - tail = (struct userid *) xmalloc (sizeof (struct userid)); - tail->id.u = uid; - if (pwent == 0) - { - sprintf (usernum_string, "%u", (unsigned) uid); - tail->name = xstrdup (usernum_string); - } - else - tail->name = xstrdup (pwent->pw_name); - - /* Add to the head of the list, so most recently used is first. */ - tail->next = user_alist; - user_alist = tail; - return tail->name; -} - -/* Translate USER to a UID, with cache. - Return NULL if there is no such user. - (We also cache which user names have no passwd entry, - so we don't keep looking them up.) */ - -uid_t * -getuidbyname (user) - char *user; -{ - register struct userid *tail; - struct passwd *pwent; - - for (tail = user_alist; tail; tail = tail->next) - /* Avoid a function call for the most common case. */ - if (*tail->name == *user && !strcmp (tail->name, user)) - return &tail->id.u; - - for (tail = nouser_alist; tail; tail = tail->next) - /* Avoid a function call for the most common case. */ - if (*tail->name == *user && !strcmp (tail->name, user)) - return 0; - - pwent = getpwnam (user); - - tail = (struct userid *) xmalloc (sizeof (struct userid)); - tail->name = xstrdup (user); - - /* Add to the head of the list, so most recently used is first. */ - if (pwent) - { - tail->id.u = pwent->pw_uid; - tail->next = user_alist; - user_alist = tail; - return &tail->id.u; - } - - tail->next = nouser_alist; - nouser_alist = tail; - return 0; -} - -/* Use the same struct as for userids. */ -static struct userid *group_alist; -static struct userid *nogroup_alist; - -/* Translate GID to a group name or a stringified number, - with cache. */ - -char * -getgroup (gid) - gid_t gid; -{ - register struct userid *tail; - struct group *grent; - char groupnum_string[20]; - - for (tail = group_alist; tail; tail = tail->next) - if (tail->id.g == gid) - return tail->name; - - grent = getgrgid (gid); - tail = (struct userid *) xmalloc (sizeof (struct userid)); - tail->id.g = gid; - if (grent == 0) - { - sprintf (groupnum_string, "%u", (unsigned int) gid); - tail->name = xstrdup (groupnum_string); - } - else - tail->name = xstrdup (grent->gr_name); - - /* Add to the head of the list, so most recently used is first. */ - tail->next = group_alist; - group_alist = tail; - return tail->name; -} - -/* Translate GROUP to a UID, with cache. - Return NULL if there is no such group. - (We also cache which group names have no group entry, - so we don't keep looking them up.) */ - -gid_t * -getgidbyname (group) - char *group; -{ - register struct userid *tail; - struct group *grent; - - for (tail = group_alist; tail; tail = tail->next) - /* Avoid a function call for the most common case. */ - if (*tail->name == *group && !strcmp (tail->name, group)) - return &tail->id.g; - - for (tail = nogroup_alist; tail; tail = tail->next) - /* Avoid a function call for the most common case. */ - if (*tail->name == *group && !strcmp (tail->name, group)) - return 0; - - grent = getgrnam (group); - - tail = (struct userid *) xmalloc (sizeof (struct userid)); - tail->name = xstrdup (group); - - /* Add to the head of the list, so most recently used is first. */ - if (grent) - { - tail->id.g = grent->gr_gid; - tail->next = group_alist; - group_alist = tail; - return &tail->id.g; - } - - tail->next = nogroup_alist; - nogroup_alist = tail; - return 0; -} diff --git a/src/bin/findutils/lib/listfile.c b/src/bin/findutils/lib/listfile.c index 39c066ef15..9147756ba2 100644 --- a/src/bin/findutils/lib/listfile.c +++ b/src/bin/findutils/lib/listfile.c @@ -1,24 +1,26 @@ /* listfile.c -- display a long listing of a file - Copyright (C) 1991, 1993 Free Software Foundation, Inc. + Copyright (C) 1991, 1993, 2000, 2003, 2004, 2007 Free Software + Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ -#ifdef HAVE_CONFIG_H -#include +#if HAVE_CONFIG_H +# include #endif +#include #include #include #include @@ -26,15 +28,30 @@ #include #include #include +#include "human.h" +#include "xalloc.h" #include "pathmax.h" +#include "error.h" +#include "filemode.h" +#include "idcache.h" -#if defined(HAVE_STRING_H) || defined(STDC_HEADERS) +#include "listfile.h" + +#if HAVE_STRING_H || STDC_HEADERS #include #else #include #endif -#ifdef STDC_HEADERS -#include + + +/* The presence of unistd.h is assumed by gnulib these days, so we + * might as well assume it too. + */ +#include /* for readlink() */ + + +#if STDC_HEADERS +# include #else char *getenv (); extern int errno; @@ -64,34 +81,68 @@ extern int errno; #endif #if defined(S_IFLNK) && !defined(S_ISLNK) #define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK) -int readlink (); #endif -//#if defined(S_ISLNK) -//#endif +/* Get or fake the disk device blocksize. + Usually defined by sys/param.h (if at all). */ +#ifndef DEV_BSIZE +# ifdef BSIZE +# define DEV_BSIZE BSIZE +# else /* !BSIZE */ +# define DEV_BSIZE 4096 +# endif /* !BSIZE */ +#endif /* !DEV_BSIZE */ /* Extract or fake data from a `struct stat'. - ST_NBLOCKS: Number of 512-byte blocks in the file - (including indirect blocks). - HP-UX, perhaps uniquely, counts st_blocks in 1024-byte units. - This workaround loses when mixing HP-UX and 4BSD filesystems, though. */ -#ifdef _POSIX_SOURCE -# define ST_NBLOCKS(statp) (((statp)->st_size + 512 - 1) / 512) -#else -# ifndef HAVE_ST_BLOCKS -# define ST_NBLOCKS(statp) (st_blocks ((statp)->st_size)) -# else -# if defined(hpux) || defined(__hpux__) -# define ST_NBLOCKS(statp) ((statp)->st_blocks * 2) -# else -# define ST_NBLOCKS(statp) ((statp)->st_blocks) -# endif -# endif + ST_BLKSIZE: Preferred I/O blocksize for the file, in bytes. + ST_NBLOCKS: Number of blocks in the file, including indirect blocks. + ST_NBLOCKSIZE: Size of blocks used when calculating ST_NBLOCKS. */ +#ifndef HAVE_STRUCT_STAT_ST_BLOCKS +# define ST_BLKSIZE(statbuf) DEV_BSIZE +# if defined(_POSIX_SOURCE) || !defined(BSIZE) /* fileblocks.c uses BSIZE. */ +# define ST_NBLOCKS(statbuf) \ + (S_ISREG ((statbuf).st_mode) \ + || S_ISDIR ((statbuf).st_mode) \ + ? (statbuf).st_size / ST_NBLOCKSIZE + ((statbuf).st_size % ST_NBLOCKSIZE != 0) : 0) +# else /* !_POSIX_SOURCE && BSIZE */ +# define ST_NBLOCKS(statbuf) \ + (S_ISREG ((statbuf).st_mode) \ + || S_ISDIR ((statbuf).st_mode) \ + ? st_blocks ((statbuf).st_size) : 0) +# endif /* !_POSIX_SOURCE && BSIZE */ +#else /* HAVE_STRUCT_STAT_ST_BLOCKS */ +/* Some systems, like Sequents, return st_blksize of 0 on pipes. */ +# define ST_BLKSIZE(statbuf) ((statbuf).st_blksize > 0 \ + ? (statbuf).st_blksize : DEV_BSIZE) +# if defined(hpux) || defined(__hpux__) || defined(__hpux) +/* HP-UX counts st_blocks in 1024-byte units. + This loses when mixing HP-UX and BSD filesystems with NFS. */ +# define ST_NBLOCKSIZE 1024 +# else /* !hpux */ +# if defined(_AIX) && defined(_I386) +/* AIX PS/2 counts st_blocks in 4K units. */ +# define ST_NBLOCKSIZE (4 * 1024) +# else /* not AIX PS/2 */ +# if defined(_CRAY) +# define ST_NBLOCKS(statbuf) \ + (S_ISREG ((statbuf).st_mode) \ + || S_ISDIR ((statbuf).st_mode) \ + ? (statbuf).st_blocks * ST_BLKSIZE(statbuf)/ST_NBLOCKSIZE : 0) +# endif /* _CRAY */ +# endif /* not AIX PS/2 */ +# endif /* !hpux */ +#endif /* HAVE_STRUCT_STAT_ST_BLOCKS */ + +#ifndef ST_NBLOCKS +# define ST_NBLOCKS(statbuf) \ + (S_ISREG ((statbuf).st_mode) \ + || S_ISDIR ((statbuf).st_mode) \ + ? (statbuf).st_blocks : 0) #endif -/* Convert B 512-byte blocks to kilobytes if K is nonzero, - otherwise return it unchanged. */ -#define convert_blocks(b, k) ((k) ? ((b) + 1) / 2 : (b)) +#ifndef ST_NBLOCKSIZE +# define ST_NBLOCKSIZE 512 +#endif #ifndef _POSIX_VERSION struct passwd *getpwuid (); @@ -107,74 +158,127 @@ struct group *getgrgid (); #endif #undef HAVE_MAJOR -char *xmalloc (); -void error (); -void mode_string (); -char *get_link_name (); -char *getgroup (); -char *getuser (); -void print_name_with_quoting (); +char * get_link_name (char *name, char *relname); +static void print_name_with_quoting (register char *p, FILE *stream); + /* NAME is the name to print. RELNAME is the path to access it from the current directory. STATP is the results of stat or lstat on it. + Use CURRENT_TIME to decide whether to print yyyy or hh:mm. + Use OUTPUT_BLOCK_SIZE to determine how to print file block counts + and sizes. STREAM is the stdio stream to print on. */ void -list_file (name, relname, statp, stream) - char *name; - char *relname; - struct stat *statp; - FILE *stream; +list_file (char *name, + char *relname, + struct stat *statp, + time_t current_time, + int output_block_size, + FILE *stream) { - static int kilobytes = -1; /* -1 = uninitialized, 0 = 512, 1 = 1024. */ - char modebuf[20]; - char timebuf[40]; - time_t current_time = time ((time_t *) 0); + char modebuf[12]; + struct tm const *when_local; + char const *user_name; + char const *group_name; + char hbuf[LONGEST_HUMAN_READABLE + 1]; - if (kilobytes == -1) - kilobytes = getenv ("POSIXLY_CORRECT") == 0; +#if HAVE_ST_DM_MODE + /* Cray DMF: look at the file's migrated, not real, status */ + strmode (statp->st_dm_mode, modebuf); +#else + strmode (statp->st_mode, modebuf); +#endif - mode_string (statp->st_mode, modebuf); - modebuf[10] = '\0'; + fprintf (stream, "%6s ", + human_readable ((uintmax_t) statp->st_ino, hbuf, + human_ceiling, + 1, 1)); - strcpy (timebuf, ctime (&statp->st_mtime)); - if (current_time > statp->st_mtime + 6L * 30L * 24L * 60L * 60L /* Old. */ - || current_time < statp->st_mtime - 60L * 60L) /* In the future. */ - { - /* The file is fairly old or in the future. - POSIX says the cutoff is 6 months old; - approximate this by 6*30 days. - Allow a 1 hour slop factor for what is considered "the future", - to allow for NFS server/client clock disagreement. - Show the year instead of the time of day. */ - strcpy (timebuf + 11, timebuf + 19); - } - timebuf[16] = 0; + fprintf (stream, "%4s ", + human_readable ((uintmax_t) ST_NBLOCKS (*statp), hbuf, + human_ceiling, + ST_NBLOCKSIZE, output_block_size)); - fprintf (stream, "%6lu ", statp->st_ino); - fprintf (stream, "%4u ", convert_blocks (ST_NBLOCKS (statp), kilobytes)); + /* modebuf includes the space between the mode and the number of links, + as the POSIX "optional alternate access method flag". */ + fprintf (stream, "%s%3lu ", modebuf, (unsigned long) statp->st_nlink); - /* The space between the mode and the number of links is the POSIX - "optional alternate access method flag". */ - fprintf (stream, "%s %3u ", modebuf, statp->st_nlink); + user_name = getuser (statp->st_uid); + if (user_name) + fprintf (stream, "%-8s ", user_name); + else + fprintf (stream, "%-8lu ", (unsigned long) statp->st_uid); - fprintf (stream, "%-8.8s ", getuser (statp->st_uid)); - - fprintf (stream, "%-8.8s ", getgroup (statp->st_gid)); + group_name = getgroup (statp->st_gid); + if (group_name) + fprintf (stream, "%-8s ", group_name); + else + fprintf (stream, "%-8lu ", (unsigned long) statp->st_gid); if (S_ISCHR (statp->st_mode) || S_ISBLK (statp->st_mode)) #ifdef HAVE_ST_RDEV - fprintf (stream, "%3u, %3u ", major (statp->st_rdev), minor (statp->st_rdev)); + fprintf (stream, "%3lu, %3lu ", + (unsigned long) major (statp->st_rdev), + (unsigned long) minor (statp->st_rdev)); #else fprintf (stream, " "); #endif else - fprintf (stream, "%8lu ", statp->st_size); + fprintf (stream, "%8s ", + human_readable ((uintmax_t) statp->st_size, hbuf, + human_ceiling, + 1, + output_block_size < 0 ? output_block_size : 1)); - fprintf (stream, "%s ", timebuf + 4); + if ((when_local = localtime (&statp->st_mtime))) + { + char init_bigbuf[256]; + char *buf = init_bigbuf; + size_t bufsize = sizeof init_bigbuf; + + /* Use strftime rather than ctime, because the former can produce + locale-dependent names for the month (%b). + + Output the year if the file is fairly old or in the future. + POSIX says the cutoff is 6 months old; + approximate this by 6*30 days. + Allow a 1 hour slop factor for what is considered "the future", + to allow for NFS server/client clock disagreement. */ + char const *fmt = + ((current_time - 6 * 30 * 24 * 60 * 60 <= statp->st_mtime + && statp->st_mtime <= current_time + 60 * 60) + ? "%b %e %H:%M" + : "%b %e %Y"); + + while (!strftime (buf, bufsize, fmt, when_local)) + buf = (char *) alloca (bufsize *= 2); + + fprintf (stream, "%s ", buf); + } + else + { + /* The time cannot be represented as a local time; + print it as a huge integer number of seconds. */ + int width = 12; + + if (statp->st_mtime < 0) + { + char const *num = human_readable (- (uintmax_t) statp->st_mtime, + hbuf, human_ceiling, 1, 1); + int sign_width = width - strlen (num); + fprintf (stream, "%*s%s ", + sign_width < 0 ? 0 : sign_width, "-", num); + } + else + fprintf (stream, "%*s ", width, + human_readable ((uintmax_t) statp->st_mtime, hbuf, + human_ceiling, + 1, 1)); + } print_name_with_quoting (name, stream); @@ -194,10 +298,8 @@ list_file (name, relname, statp, stream) putc ('\n', stream); } -void -print_name_with_quoting (p, stream) - register char *p; - FILE *stream; +static void +print_name_with_quoting (register char *p, FILE *stream) { register unsigned char c; @@ -248,9 +350,7 @@ print_name_with_quoting (p, stream) #ifdef S_ISLNK char * -get_link_name (name, relname) - char *name; - char *relname; +get_link_name (char *name, char *relname) { register char *linkname; register int linklen; diff --git a/src/bin/findutils/lib/listfile.h b/src/bin/findutils/lib/listfile.h new file mode 100644 index 0000000000..4433259e76 --- /dev/null +++ b/src/bin/findutils/lib/listfile.h @@ -0,0 +1,26 @@ +/* listfile.h -- display a long listing of a file + Copyright (C) 1991, 1993, 2000 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + + +#if !defined LISTFILE_H +# define LISTFILE_H + +void list_file (char *name, char *relname, struct stat *statp, time_t current_time, int output_block_size, FILE *stream); + + + +#endif diff --git a/src/bin/findutils/lib/memcmp.c b/src/bin/findutils/lib/memcmp.c deleted file mode 100644 index 339b5818e7..0000000000 --- a/src/bin/findutils/lib/memcmp.c +++ /dev/null @@ -1,32 +0,0 @@ -/* memcmp.c -- compare memory. - Return: - <0 if S1 < S2, - 0 if strings are identical, - >0 if S1 > S2. - Stops looking after N characters. Doesn't stop at nulls. - In the public domain. - By David MacKenzie . */ - -#include - -int -#if __STDC__ -memcmp (void const *v1, void const *v2, size_t n) -{ - register char *s1 = (char *) v1, *s2 = (char *) v2; -#else -memcmp (s1, s2, n) - register char *s1, *s2; - register unsigned n; -{ -#endif - register int diff; - - while (n--) - { - diff = *s1++ - *s2++; - if (diff) - return diff; - } - return 0; -} diff --git a/src/bin/findutils/lib/mktime.c b/src/bin/findutils/lib/mktime.c deleted file mode 100644 index d441d8d8c4..0000000000 --- a/src/bin/findutils/lib/mktime.c +++ /dev/null @@ -1,502 +0,0 @@ -/* Copyright (C) 1993, 1994 Free Software Foundation, Inc. - Contributed by Noel Cragg (noel@cs.oberlin.edu), with fixes by - Michael E. Calwas (calwas@ttd.teradyne.com) and - Wade Hampton (tasi029@tmn.com). - -This file is part of the GNU C Library. - -The GNU C Library is free software; you can redistribute it and/or -modify it under the terms of the GNU Library General Public License as -published by the Free Software Foundation; either version 2 of the -License, or (at your option) any later version. - -The GNU C Library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Library General Public License for more details. - -You should have received a copy of the GNU Library General Public -License along with the GNU C Library; see the file COPYING.LIB. If -not, write to the Free Software Foundation, Inc., 675 Mass Ave, -Cambridge, MA 02139, USA. */ - -/* Define this to have a standalone program to test this implementation of - mktime. */ -/* #define DEBUG */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include /* Some systems define `time_t' here. */ -#include - - -#ifndef __isleap -/* Nonzero if YEAR is a leap year (every 4 years, - except every 100th isn't, and every 400th is). */ -#define __isleap(year) \ - ((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0)) -#endif - -#ifndef __P -#if defined (__GNUC__) || (defined (__STDC__) && __STDC__) -#define __P(args) args -#else -#define __P(args) () -#endif /* GCC. */ -#endif /* Not __P. */ - -/* How many days are in each month. */ -const unsigned short int __mon_lengths[2][12] = - { - /* Normal years. */ - { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, - /* Leap years. */ - { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } - }; - - -static int times_through_search; /* This library routine should never - hang -- make sure we always return - when we're searching for a value */ - - -#ifdef DEBUG - -#include -#include - -int debugging_enabled = 0; - -/* Print the values in a `struct tm'. */ -static void -printtm (it) - struct tm *it; -{ - printf ("%02d/%02d/%04d %02d:%02d:%02d (%s) yday:%03d dst:%d gmtoffset:%ld", - it->tm_mon + 1, - it->tm_mday, - it->tm_year + 1900, - it->tm_hour, - it->tm_min, - it->tm_sec, - it->tm_zone, - it->tm_yday, - it->tm_isdst, - it->tm_gmtoff); -} -#endif - - -static time_t -dist_tm (t1, t2) - struct tm *t1; - struct tm *t2; -{ - time_t distance = 0; - unsigned long int v1, v2; - int diff_flag = 0; - - v1 = v2 = 0; - -#define doit(x, secs) \ - v1 += t1->x * secs; \ - v2 += t2->x * secs; \ - if (!diff_flag) \ - { \ - if (t1->x < t2->x) \ - diff_flag = -1; \ - else if (t1->x > t2->x) \ - diff_flag = 1; \ - } - - doit (tm_year, 31536000); /* Okay, not all years have 365 days. */ - doit (tm_mon, 2592000); /* Okay, not all months have 30 days. */ - doit (tm_mday, 86400); - doit (tm_hour, 3600); - doit (tm_min, 60); - doit (tm_sec, 1); - -#undef doit - - /* We should also make sure that the sign of DISTANCE is correct -- if - DIFF_FLAG is positive, the distance should be positive and vice versa. */ - - distance = (v1 > v2) ? (v1 - v2) : (v2 - v1); - if (diff_flag < 0) - distance = -distance; - - if (times_through_search > 20) /* Arbitrary # of calls, but makes sure we - never hang if there's a problem with - this algorithm. */ - { - distance = diff_flag; - } - - /* We need this DIFF_FLAG business because it is forseeable that the - distance may be zero when, in actuality, the two structures are - different. This is usually the case when the dates are 366 days apart - and one of the years is a leap year. */ - - if (distance == 0 && diff_flag) - distance = 86400 * diff_flag; - - return distance; -} - - -/* MKTIME converts the values in a struct tm to a time_t. The values - in tm_wday and tm_yday are ignored; other values can be put outside - of legal ranges since they will be normalized. This routine takes - care of that normalization. */ - -void -do_normalization (tmptr) - struct tm *tmptr; -{ - -#define normalize(foo,x,y,bar); \ - while (tmptr->foo < x) \ - { \ - tmptr->bar--; \ - tmptr->foo = (y - (x - tmptr->foo) + 1); \ - } \ - while (tmptr->foo > y) \ - { \ - tmptr->foo = (x + (tmptr->foo - y) - 1); \ - tmptr->bar++; \ - } - - normalize (tm_sec, 0, 59, tm_min); - normalize (tm_min, 0, 59, tm_hour); - normalize (tm_hour, 0, 23, tm_mday); - - /* Do the month first, so day range can be found. */ - normalize (tm_mon, 0, 11, tm_year); - - /* Since the day range modifies the month, we should be careful how - we reference the array of month lengths -- it is possible that - the month will go negative, hence the modulo... - - Also, tm_year is the year - 1900, so we have to 1900 to have it - work correctly. */ - - normalize (tm_mday, 1, - __mon_lengths[__isleap (tmptr->tm_year + 1900)] - [((tmptr->tm_mon < 0) - ? (12 + (tmptr->tm_mon % 12)) - : (tmptr->tm_mon % 12)) ], - tm_mon); - - /* Do the month again, because the day may have pushed it out of range. */ - normalize (tm_mon, 0, 11, tm_year); - - /* Do the day again, because the month may have changed the range. */ - normalize (tm_mday, 1, - __mon_lengths[__isleap (tmptr->tm_year + 1900)] - [((tmptr->tm_mon < 0) - ? (12 + (tmptr->tm_mon % 12)) - : (tmptr->tm_mon % 12)) ], - tm_mon); - -#ifdef DEBUG - if (debugging_enabled) - { - printf (" After normalizing:\n "); - printtm (tmptr); - putchar ('\n'); - } -#endif - -} - - -/* Here's where the work gets done. */ - -#define BAD_STRUCT_TM ((time_t) -1) - -time_t -_mktime_internal (timeptr, producer) - struct tm *timeptr; - struct tm *(*producer) __P ((const time_t *)); -{ - struct tm our_tm; /* our working space */ - struct tm *me = &our_tm; /* a pointer to the above */ - time_t result; /* the value we return */ - - *me = *timeptr; /* copy the struct tm that was passed - in by the caller */ - - - /***************************/ - /* Normalize the structure */ - /***************************/ - - /* This routine assumes that the value of TM_ISDST is -1, 0, or 1. - If the user didn't pass it in that way, fix it. */ - - if (me->tm_isdst > 0) - me->tm_isdst = 1; - else if (me->tm_isdst < 0) - me->tm_isdst = -1; - - do_normalization (me); - - /* Get out of here if it's not possible to represent this struct. - If any of the values in the normalized struct tm are negative, - our algorithms won't work. Luckily, we only need to check the - year at this point; normalization guarantees that all values will - be in correct ranges EXCEPT the year. */ - - if (me->tm_year < 0) - return BAD_STRUCT_TM; - - /*************************************************/ - /* Find the appropriate time_t for the structure */ - /*************************************************/ - - /* Modified b-search -- make intelligent guesses as to where the - time might lie along the timeline, assuming that our target time - lies a linear distance (w/o considering time jumps of a - particular region). - - Assume that time does not fluctuate at all along the timeline -- - e.g., assume that a day will always take 86400 seconds, etc. -- - and come up with a hypothetical value for the time_t - representation of the struct tm TARGET, in relation to the guess - variable -- it should be pretty close! - - After testing this, the maximum number of iterations that I had - on any number that I tried was 3! Not bad. - - The reason this is not a subroutine is that we will modify some - fields in the struct tm (yday and mday). I've never felt good - about side-effects when writing structured code... */ - - { - struct tm *guess_tm; - time_t guess = 0; - time_t distance = 0; - time_t last_distance = 0; - - times_through_search = 0; - - do - { - guess += distance; - - times_through_search++; - - guess_tm = (*producer) (&guess); - -#ifdef DEBUG - if (debugging_enabled) - { - printf (" Guessing time_t == %d\n ", (int) guess); - printtm (guess_tm); - putchar ('\n'); - } -#endif - - /* How far is our guess from the desired struct tm? */ - distance = dist_tm (me, guess_tm); - - /* Handle periods of time where a period of time is skipped. - For example, 2:15 3 April 1994 does not exist, because DST - is in effect. The distance function will alternately - return values of 3600 and -3600, because it doesn't know - that the requested time doesn't exist. In these situations - (even if the skip is not exactly an hour) the distances - returned will be the same, but alternating in sign. We - want the later time, so check to see that the distance is - oscillating and we've chosen the correct of the two - possibilities. - - Useful: 3 Apr 94 765356300, 30 Oct 94 783496000 */ - - if ((distance == -last_distance) && (distance < last_distance)) - { - /* If the caller specified that the DST flag was off, it's - not possible to represent this time. */ - if (me->tm_isdst == 0) - { -#ifdef DEBUG - printf (" Distance is oscillating -- dst flag nixes struct!\n"); -#endif - return BAD_STRUCT_TM; - } - -#ifdef DEBUG - printf (" Distance is oscillating -- chose the later time.\n"); -#endif - distance = 0; - } - - if ((distance == 0) && (me->tm_isdst != -1) - && (me->tm_isdst != guess_tm->tm_isdst)) - { - /* If we're in this code, we've got the right time but the - wrong daylight savings flag. We need to move away from - the time that we have and approach the other time from - the other direction. That is, if I've requested the - non-DST version of a time and I get the DST version - instead, I want to put us forward in time and search - backwards to get the other time. I checked all of the - configuration files for the tz package -- no entry - saves more than two hours, so I think we'll be safe by - moving 24 hours in one direction. IF THE AMOUNT OF - TIME SAVED IN THE CONFIGURATION FILES CHANGES, THIS - VALUE MAY NEED TO BE ADJUSTED. Luckily, we can never - have more than one level of overlaps, or this would - never work. */ - -#define SKIP_VALUE 86400 - - if (guess_tm->tm_isdst == 0) - /* we got the later one, but want the earlier one */ - distance = -SKIP_VALUE; - else - distance = SKIP_VALUE; - -#ifdef DEBUG - printf (" Got the right time, wrong DST value -- adjusting\n"); -#endif - } - - last_distance = distance; - - } while (distance != 0); - - /* Check to see that the dst flag matches */ - - if (me->tm_isdst != -1) - { - if (me->tm_isdst != guess_tm->tm_isdst) - { -#ifdef DEBUG - printf (" DST flag doesn't match! FIXME?\n"); -#endif - return BAD_STRUCT_TM; - } - } - - result = guess; /* Success! */ - - /* On successful completion, the values of tm_wday and tm_yday - have to be set appropriately. */ - - /* me->tm_yday = guess_tm->tm_yday; - me->tm_mday = guess_tm->tm_mday; */ - - *me = *guess_tm; - } - - /* Update the caller's version of the structure */ - - *timeptr = *me; - - return result; -} - -time_t -#ifdef DEBUG /* make it work even if the system's - libc has it's own mktime routine */ -my_mktime (timeptr) -#else -mktime (timeptr) -#endif - struct tm *timeptr; -{ - return _mktime_internal (timeptr, localtime); -} - -#ifdef DEBUG -void -main (argc, argv) - int argc; - char *argv[]; -{ - int time; - int result_time; - struct tm *tmptr; - - if (argc == 1) - { - long q; - - printf ("starting long test...\n"); - - for (q = 10000000; q < 1000000000; q += 599) - { - struct tm *tm = localtime ((time_t *) &q); - if ((q % 10000) == 0) { printf ("%ld\n", q); fflush (stdout); } - if (q != my_mktime (tm)) - { printf ("failed for %ld\n", q); fflush (stdout); } - } - - printf ("test finished\n"); - - exit (0); - } - - if (argc != 2) - { - printf ("wrong # of args\n"); - exit (0); - } - - debugging_enabled = 1; /* We want to see the info */ - - ++argv; - time = atoi (*argv); - - tmptr = localtime ((time_t *) &time); - printf ("Localtime tells us that a time_t of %d represents\n ", time); - printtm (tmptr); - putchar ('\n'); - - printf (" Given localtime's return val, mktime returns %d which is\n ", - (int) my_mktime (tmptr)); - printtm (tmptr); - putchar ('\n'); - -#if 0 - tmptr->tm_sec -= 20; - tmptr->tm_min -= 20; - tmptr->tm_hour -= 20; - tmptr->tm_mday -= 20; - tmptr->tm_mon -= 20; - tmptr->tm_year -= 20; - tmptr->tm_gmtoff -= 20000; /* This has no effect! */ - tmptr->tm_zone = NULL; /* Nor does this! */ - tmptr->tm_isdst = -1; -#endif - - tmptr->tm_hour += 1; - tmptr->tm_isdst = -1; - - printf ("\n\nchanged ranges: "); - printtm (tmptr); - putchar ('\n'); - - result_time = my_mktime (tmptr); - printf ("\nmktime: %d\n", result_time); - - tmptr->tm_isdst = 0; - - printf ("\n\nchanged ranges: "); - printtm (tmptr); - putchar ('\n'); - - result_time = my_mktime (tmptr); - printf ("\nmktime: %d\n", result_time); -} -#endif /* DEBUG */ - - -/* -Local Variables: -compile-command: "gcc -g mktime.c -o mktime -DDEBUG" -End: -*/ diff --git a/src/bin/findutils/lib/modechange.c b/src/bin/findutils/lib/modechange.c deleted file mode 100644 index 3862599e21..0000000000 --- a/src/bin/findutils/lib/modechange.c +++ /dev/null @@ -1,341 +0,0 @@ -/* modechange.c -- file mode manipulation - Copyright (C) 1989, 1990 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -/* Written by David MacKenzie */ - -/* The ASCII mode string is compiled into a linked list of `struct - modechange', which can then be applied to each file to be changed. - We do this instead of re-parsing the ASCII string for each file - because the compiled form requires less computation to use; when - changing the mode of many files, this probably results in a - performance gain. */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include -#include -#include "modechange.h" - -#ifdef STDC_HEADERS -#include -#else -char *malloc (); -#endif - -#ifndef NULL -#define NULL 0 -#endif - -#ifdef STAT_MACROS_BROKEN -#undef S_ISDIR -#endif /* STAT_MACROS_BROKEN. */ - -#if !defined(S_ISDIR) && defined(S_IFDIR) -#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) -#endif - -/* Return newly allocated memory to hold one element of type TYPE. */ -#define talloc(type) ((type *) malloc (sizeof (type))) - -#define isodigit(c) ((c) >= '0' && (c) <= '7') - -static int oatoi (); - -/* Return a linked list of file mode change operations created from - MODE_STRING, an ASCII string that contains either an octal number - specifying an absolute mode, or symbolic mode change operations with - the form: - [ugoa...][[+-=][rwxXstugo...]...][,...] - MASKED_OPS is a bitmask indicating which symbolic mode operators (=+-) - should not affect bits set in the umask when no users are given. - Operators not selected in MASKED_OPS ignore the umask. - - Return MODE_INVALID if `mode_string' does not contain a valid - representation of file mode change operations; - return MODE_MEMORY_EXHAUSTED if there is insufficient memory. */ - -struct mode_change * -mode_compile (mode_string, masked_ops) - register char *mode_string; - unsigned masked_ops; -{ - struct mode_change *head; /* First element of the linked list. */ - struct mode_change *change; /* An element of the linked list. */ - int i; /* General purpose temporary. */ - unsigned short umask_value; /* The umask value (surprise). */ - unsigned short affected_bits; /* Which bits in the mode are operated on. */ - unsigned short affected_masked; /* `affected_bits' modified by umask. */ - unsigned ops_to_mask; /* Operators to actually use umask on. */ - - i = oatoi (mode_string); - if (i >= 0) - { - if (i > 07777) - return MODE_INVALID; - head = talloc (struct mode_change); - if (head == NULL) - return MODE_MEMORY_EXHAUSTED; - head->next = NULL; - head->op = '='; - head->flags = 0; - head->value = i; - head->affected = 07777; /* Affect all permissions. */ - return head; - } - - umask_value = umask (0); - umask (umask_value); /* Restore the old value. */ - - head = NULL; -#ifdef lint - change = NULL; -#endif - --mode_string; - - /* One loop iteration for each "ugoa...=+-rwxXstugo...[=+-rwxXstugo...]". */ - do - { - affected_bits = 0; - ops_to_mask = 0; - /* Turn on all the bits in `affected_bits' for each group given. */ - for (++mode_string;; ++mode_string) - switch (*mode_string) - { - case 'u': - affected_bits |= 04700; - break; - case 'g': - affected_bits |= 02070; - break; - case 'o': - affected_bits |= 01007; - break; - case 'a': - affected_bits |= 07777; - break; - default: - goto no_more_affected; - } - - no_more_affected: - /* If none specified, affect all bits, except perhaps those - set in the umask. */ - if (affected_bits == 0) - { - affected_bits = 07777; - ops_to_mask = masked_ops; - } - - while (*mode_string == '=' || *mode_string == '+' || *mode_string == '-') - { - /* Add the element to the tail of the list, so the operations - are performed in the correct order. */ - if (head == NULL) - { - head = talloc (struct mode_change); - if (head == NULL) - return MODE_MEMORY_EXHAUSTED; - change = head; - } - else - { - change->next = talloc (struct mode_change); - if (change->next == NULL) - { - mode_free (change); - return MODE_MEMORY_EXHAUSTED; - } - change = change->next; - } - - change->next = NULL; - change->op = *mode_string; /* One of "=+-". */ - affected_masked = affected_bits; - if (ops_to_mask & (*mode_string == '=' ? MODE_MASK_EQUALS - : *mode_string == '+' ? MODE_MASK_PLUS - : MODE_MASK_MINUS)) - affected_masked &= ~umask_value; - change->affected = affected_masked; - change->value = 0; - change->flags = 0; - - /* Set `value' according to the bits set in `affected_masked'. */ - for (++mode_string;; ++mode_string) - switch (*mode_string) - { - case 'r': - change->value |= 00444 & affected_masked; - break; - case 'w': - change->value |= 00222 & affected_masked; - break; - case 'X': - change->flags |= MODE_X_IF_ANY_X; - /* Fall through. */ - case 'x': - change->value |= 00111 & affected_masked; - break; - case 's': - /* Set the setuid/gid bits if `u' or `g' is selected. */ - change->value |= 06000 & affected_masked; - break; - case 't': - /* Set the "save text image" bit if `o' is selected. */ - change->value |= 01000 & affected_masked; - break; - case 'u': - /* Set the affected bits to the value of the `u' bits - on the same file. */ - if (change->value) - goto invalid; - change->value = 00700; - change->flags |= MODE_COPY_EXISTING; - break; - case 'g': - /* Set the affected bits to the value of the `g' bits - on the same file. */ - if (change->value) - goto invalid; - change->value = 00070; - change->flags |= MODE_COPY_EXISTING; - break; - case 'o': - /* Set the affected bits to the value of the `o' bits - on the same file. */ - if (change->value) - goto invalid; - change->value = 00007; - change->flags |= MODE_COPY_EXISTING; - break; - default: - goto no_more_values; - } - no_more_values:; - } - } while (*mode_string == ','); - if (*mode_string == 0) - return head; -invalid: - mode_free (head); - return MODE_INVALID; -} - -/* Return file mode OLDMODE, adjusted as indicated by the list of change - operations CHANGES. If OLDMODE is a directory, the type `X' - change affects it even if no execute bits were set in OLDMODE. - The returned value has the S_IFMT bits cleared. */ - -unsigned short -mode_adjust (oldmode, changes) - unsigned oldmode; - register struct mode_change *changes; -{ - unsigned short newmode; /* The adjusted mode and one operand. */ - unsigned short value; /* The other operand. */ - - newmode = oldmode & 07777; - - for (; changes; changes = changes->next) - { - if (changes->flags & MODE_COPY_EXISTING) - { - /* Isolate in `value' the bits in `newmode' to copy, given in - the mask `changes->value'. */ - value = newmode & changes->value; - - if (changes->value & 00700) - /* Copy `u' permissions onto `g' and `o'. */ - value |= (value >> 3) | (value >> 6); - else if (changes->value & 00070) - /* Copy `g' permissions onto `u' and `o'. */ - value |= (value << 3) | (value >> 3); - else - /* Copy `o' permissions onto `u' and `g'. */ - value |= (value << 3) | (value << 6); - - /* In order to change only `u', `g', or `o' permissions, - or some combination thereof, clear unselected bits. - This can not be done in mode_compile because the value - to which the `changes->affected' mask is applied depends - on the old mode of each file. */ - value &= changes->affected; - } - else - { - value = changes->value; - /* If `X', do not affect the execute bits if the file is not a - directory and no execute bits are already set. */ - if ((changes->flags & MODE_X_IF_ANY_X) - && !S_ISDIR (oldmode) - && (newmode & 00111) == 0) - value &= ~00111; /* Clear the execute bits. */ - } - - switch (changes->op) - { - case '=': - /* Preserve the previous values in `newmode' of bits that are - not affected by this change operation. */ - newmode = (newmode & ~changes->affected) | value; - break; - case '+': - newmode |= value; - break; - case '-': - newmode &= ~value; - break; - } - } - return newmode; -} - -/* Free the memory used by the list of file mode change operations - CHANGES. */ - -void -mode_free (changes) - register struct mode_change *changes; -{ - register struct mode_change *next; - - while (changes) - { - next = changes->next; - free (changes); - changes = next; - } -} - -/* Return a positive integer containing the value of the ASCII - octal number S. If S is not an octal number, return -1. */ - -static int -oatoi (s) - char *s; -{ - register int i; - - if (*s == 0) - return -1; - for (i = 0; isodigit (*s); ++s) - i = i * 8 + *s - '0'; - if (*s) - return -1; - return i; -} diff --git a/src/bin/findutils/lib/modechange.h b/src/bin/findutils/lib/modechange.h deleted file mode 100644 index 4a29883044..0000000000 --- a/src/bin/findutils/lib/modechange.h +++ /dev/null @@ -1,55 +0,0 @@ -/* modechange.h -- definitions for file mode manipulation - Copyright (C) 1989, 1990 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -/* Masks for the `flags' field in a `struct mode_change'. */ - -/* Affect the execute bits only if at least one execute bit is set already, - or if the file is a directory. */ -#define MODE_X_IF_ANY_X 01 - -/* If set, copy some existing permissions for u, g, or o onto the other two. - Which of u, g, or o is copied is determined by which bits are set in the - `value' field. */ -#define MODE_COPY_EXISTING 02 - -struct mode_change -{ - char op; /* One of "=+-". */ - char flags; /* Special operations. */ - unsigned short affected; /* Set for u/g/o/s/s/t, if to be affected. */ - unsigned short value; /* Bits to add/remove. */ - struct mode_change *next; /* Link to next change in list. */ -}; - -/* Masks for mode_compile argument. */ -#define MODE_MASK_EQUALS 1 -#define MODE_MASK_PLUS 2 -#define MODE_MASK_MINUS 4 - -/* Error return values for mode_compile. */ -#define MODE_INVALID (struct mode_change *) 0 -#define MODE_MEMORY_EXHAUSTED (struct mode_change *) 1 - -#ifdef __STDC__ -struct mode_change *mode_compile (char *, unsigned); -unsigned short mode_adjust (unsigned, struct mode_change *); -void mode_free (struct mode_change *); -#else -struct mode_change *mode_compile (); -unsigned short mode_adjust (); -void mode_free (); -#endif diff --git a/src/bin/findutils/lib/modetype.h b/src/bin/findutils/lib/modetype.h index fd4092bfa6..5f201a7da1 100644 --- a/src/bin/findutils/lib/modetype.h +++ b/src/bin/findutils/lib/modetype.h @@ -1,25 +1,28 @@ /* modetype.h -- file type bits definitions for POSIX systems Requires sys/types.h sys/stat.h. - Copyright (C) 1990 Free Software Foundation, Inc. + Copyright (C) 1990, 2001, 2003, 2004 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ /* POSIX.1 doesn't mention the S_IFMT bits; instead, it uses S_IStype test macros. To make storing file types more convenient, define them; the values don't need to correspond to what the kernel uses, because of the way we use them. */ +#ifndef INC_MODETYPE_H +#define INC_MODETYPE_H 1 + #ifndef S_IFMT /* Doesn't have traditional Unix macros. */ #define S_IFBLK 1 #define S_IFCHR 2 @@ -34,6 +37,9 @@ #ifdef S_ISSOCK #define S_IFSOCK 64 #endif +#ifdef S_ISDOOR +#define S_IFDOOR 128 +#endif #endif /* !S_IFMT */ #ifdef STAT_MACROS_BROKEN @@ -44,6 +50,7 @@ #undef S_ISFIFO #undef S_ISLNK #undef S_ISSOCK +#undef S_ISDOOR #undef S_ISMPB #undef S_ISMPC #undef S_ISNWK @@ -72,6 +79,9 @@ #if !defined(S_ISSOCK) && defined(S_IFSOCK) #define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK) #endif +#if !defined(S_ISDOOR) && defined(S_IFDOOR) +#define S_ISDOOR(m) (((m) & S_IFMT) == S_IFDOOR) +#endif #if !defined(S_ISMPB) && defined(S_IFMPB) /* V7 */ #define S_ISMPB(m) (((m) & S_IFMT) == S_IFMPB) #define S_ISMPC(m) (((m) & S_IFMT) == S_IFMPC) @@ -79,3 +89,5 @@ #if !defined(S_ISNWK) && defined(S_IFNWK) /* HP/UX */ #define S_ISNWK(m) (((m) & S_IFMT) == S_IFNWK) #endif + +#endif diff --git a/src/bin/findutils/lib/nextelem.c b/src/bin/findutils/lib/nextelem.c index 4b9ddc1fb5..e9c95107ff 100644 --- a/src/bin/findutils/lib/nextelem.c +++ b/src/bin/findutils/lib/nextelem.c @@ -1,21 +1,21 @@ /* Return the next element of a path. - Copyright (C) 1992 Free Software Foundation, Inc. + Copyright (C) 1992, 2003, 2004, 2005 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ -/* Written by David MacKenzie , +/* Written by David MacKenzie , inspired by John P. Rouillard . */ #ifdef HAVE_CONFIG_H @@ -31,9 +31,12 @@ #define strchr index #endif #endif +#if defined(STDC_HEADERS) +#include +#endif + +#include "nextelem.h" -char *strdup (); -void free (); /* Return the next element of a colon-separated path. A null entry in the path is equivalent to "." (the current directory). @@ -43,8 +46,7 @@ void free (); return NULL if there are no more elements. */ char * -next_element (new_path) - char *new_path; +next_element (const char *new_path, int curdir_ok) { static char *path = NULL; /* Freshly allocated copy of NEW_PATH. */ static char *end; /* Start of next element to return. */ @@ -65,7 +67,7 @@ next_element (new_path) if (final_colon) { final_colon = 0; - return "."; + return curdir_ok ? "." : ""; } return NULL; } @@ -78,7 +80,7 @@ next_element (new_path) { /* An empty path element. */ *end++ = '\0'; - return "."; + return curdir_ok ? "." : ""; } else if (end == NULL) { diff --git a/src/bin/findutils/lib/nextelem.h b/src/bin/findutils/lib/nextelem.h new file mode 100644 index 0000000000..83c71f941f --- /dev/null +++ b/src/bin/findutils/lib/nextelem.h @@ -0,0 +1,26 @@ +/* Return the next element of a path. + Copyright (C) 1992, 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +/* Written by David MacKenzie , + inspired by John P. Rouillard . */ + +#ifndef INC_NEXTELEM_H +#define INC_NEXTELEM_H 1 + +char *next_element (const char *path, int curdir_ok); + +#endif diff --git a/src/bin/findutils/lib/pathmax.h b/src/bin/findutils/lib/pathmax.h deleted file mode 100644 index 00fb0b514e..0000000000 --- a/src/bin/findutils/lib/pathmax.h +++ /dev/null @@ -1,53 +0,0 @@ -/* Define PATH_MAX somehow. Requires sys/types.h. - Copyright (C) 1992 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -#ifndef _PATHMAX_H -#define _PATHMAX_H - -#ifdef HAVE_UNISTD_H -#include -#endif - -/* Non-POSIX BSD systems might have gcc's limits.h, which doesn't define - PATH_MAX but might cause redefinition warnings when sys/param.h is - later included (as on MORE/BSD 4.3). */ -#if defined(_POSIX_VERSION) || (defined(HAVE_LIMITS_H) && !defined(__GNUC__)) -#include -#endif - -#ifndef _POSIX_PATH_MAX -#define _POSIX_PATH_MAX 255 -#endif - -#if !defined(PATH_MAX) && defined(_PC_PATH_MAX) -#define PATH_MAX (pathconf ("/", _PC_PATH_MAX) < 1 ? 1024 : pathconf ("/", _PC_PATH_MAX)) -#endif - -/* Don't include sys/param.h if it already has been. */ -#if defined(HAVE_SYS_PARAM_H) && !defined(PATH_MAX) && !defined(MAXPATHLEN) -#include -#endif - -#if !defined(PATH_MAX) && defined(MAXPATHLEN) -#define PATH_MAX MAXPATHLEN -#endif - -#ifndef PATH_MAX -#define PATH_MAX _POSIX_PATH_MAX -#endif - -#endif /* _PATHMAX_H */ diff --git a/src/bin/findutils/lib/printquoted.c b/src/bin/findutils/lib/printquoted.c new file mode 100644 index 0000000000..c83f7990f6 --- /dev/null +++ b/src/bin/findutils/lib/printquoted.c @@ -0,0 +1,85 @@ +/* printquoted.c -- print a specified string with any necessary quoting. + + Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, + 2003, 2004, 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +/* Get mbstate_t, mbrtowc(), mbsinit(), wcwidth(). */ +#if HAVE_WCHAR_H +# include +#endif + + + +#include "xalloc.h" +#include "printquoted.h" + + +/* + * Print S according to the format FORMAT, but if the destination is a tty, + * convert any potentially-dangerous characters. The logic in this function + * was taken from ls.c in coreutils (at Sun Jun 5 20:42:51 2005 UTC). + */ +void +print_quoted (FILE *fp, + const struct quoting_options *qopts, + bool dest_is_tty, + const char *format, + const char *s) +{ + if (dest_is_tty) + { + char smallbuf[BUFSIZ]; + size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, s, -1, qopts); + char *buf; + if (len < sizeof smallbuf) + buf = smallbuf; + else + { + /* The original coreutils code uses alloca(), but I don't + * want to take on the anguish of introducing alloca() to + * 'find'. + */ + buf = xmalloc (len + 1); + quotearg_buffer (buf, len + 1, s, -1, qopts); + } + + /* Replace any remaining funny characters with '?'. */ + len = qmark_chars(buf, len); + + fprintf(fp, format, buf); /* Print the quoted version */ + if (buf != smallbuf) + { + free(buf); + buf = NULL; + } + } + else + { + /* no need to quote things. */ + fprintf(fp, format, s); + } + +} + diff --git a/src/bin/findutils/lib/printquoted.h b/src/bin/findutils/lib/printquoted.h new file mode 100644 index 0000000000..e65cf4b4e5 --- /dev/null +++ b/src/bin/findutils/lib/printquoted.h @@ -0,0 +1,34 @@ +/* Print a string, appropriately quoted. + + Copyright 1997, 1999, 2001, 2003, 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#if !defined PRINTQUOTED_H +# define PRINTQUOTED_H + +#include "quote.h" +#include "quotearg.h" + + +#include +#include + + +size_t qmark_chars(char *buf, size_t len); +void print_quoted (FILE *fp, const struct quoting_options *qopts, bool dest_is_tty, const char *format, const char *s); + + +#endif diff --git a/src/bin/findutils/lib/qmark.c b/src/bin/findutils/lib/qmark.c new file mode 100644 index 0000000000..2462ac0e2e --- /dev/null +++ b/src/bin/findutils/lib/qmark.c @@ -0,0 +1,237 @@ +/* pred.c -- execute the expression tree. + Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, + 2003, 2004 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifdef HAVE_CONFIG_H +#include +#endif + +# include +# include +#include + +#if HAVE_STRING_H || STDC_HEADERS +#include +#else +#include +#endif + + +/* Get mbstate_t, mbrtowc(), mbsinit(), wcwidth(). */ +#if HAVE_WCHAR_H +# include +#endif + +#include "printquoted.h" + + +/* + This comment, IN_CTYPE_DOMAIN and ISPRINT were borrowed from + coreutils at Sun Jun 5 21:17:40 2005 UTC. + + Jim Meyering writes: + + "... Some ctype macros are valid only for character codes that + isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when + using /bin/cc or gcc but without giving an ansi option). So, all + ctype uses should be through macros like ISPRINT... If + STDC_HEADERS is defined, then autoconf has verified that the ctype + macros don't need to be guarded with references to isascii. ... + Defining isascii to 1 should let any compiler worth its salt + eliminate the && through constant folding." + + Bruno Haible adds: + + "... Furthermore, isupper(c) etc. have an undefined result if c is + outside the range -1 <= c <= 255. One is tempted to write isupper(c) + with c being of type `char', but this is wrong if c is an 8-bit + character >= 128 which gets sign-extended to a negative value. + The macro ISUPPER protects against this as well." */ + + + + +/* ISPRINT is defined in on at least Solaris2.6 systems. */ +#undef ISPRINT +#define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c)) + +#if STDC_HEADERS || (!defined (isascii) && !HAVE_ISASCII) +# define IN_CTYPE_DOMAIN(c) 1 +#else +# define IN_CTYPE_DOMAIN(c) isascii(c) +#endif + + + + + +/* Convert a possibly-signed character to an unsigned character. This is + * a bit safer than casting to unsigned char, since it catches some type + * errors that the cast doesn't. + * + * This code taken from coreutils' system.h header at + * Sun Jun 5 21:05:21 2005 UTC. + */ +static inline unsigned char to_uchar (char ch) +{ + return ch; +} + + + +static size_t +unibyte_qmark_chars(char *buf, size_t len) +{ + char *p = buf; + char const *plimit = buf + len; + + while (p < plimit) + { + if (! ISPRINT (to_uchar (*p))) + *p = '?'; + p++; + } + return len; +} + + +#if HAVE_MBRTOWC +static size_t +multibyte_qmark_chars(char *buf, size_t len) +{ + if (MB_CUR_MAX <= 1) + { + return unibyte_qmark_chars(buf, len); + } + else + { + char const *p = buf; + char const *plimit = buf + len; + char *q = buf; + + while (p < plimit) + switch (*p) + { + case ' ': case '!': case '"': case '#': case '%': + case '&': case '\'': case '(': case ')': case '*': + case '+': case ',': case '-': case '.': case '/': + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + case ':': case ';': case '<': case '=': case '>': + case '?': + case 'A': case 'B': case 'C': case 'D': case 'E': + case 'F': case 'G': case 'H': case 'I': case 'J': + case 'K': case 'L': case 'M': case 'N': case 'O': + case 'P': case 'Q': case 'R': case 'S': case 'T': + case 'U': case 'V': case 'W': case 'X': case 'Y': + case 'Z': + case '[': case '\\': case ']': case '^': case '_': + case 'a': case 'b': case 'c': case 'd': case 'e': + case 'f': case 'g': case 'h': case 'i': case 'j': + case 'k': case 'l': case 'm': case 'n': case 'o': + case 'p': case 'q': case 'r': case 's': case 't': + case 'u': case 'v': case 'w': case 'x': case 'y': + case 'z': case '{': case '|': case '}': case '~': + /* These characters are printable ASCII characters. */ + *q++ = *p++; + break; + default: + /* If we have a multibyte sequence, copy it until we + reach its end, replacing each non-printable multibyte + character with a single question mark. */ + { + mbstate_t mbstate; + memset (&mbstate, 0, sizeof mbstate); + do + { + wchar_t wc; + size_t bytes; + int w; + + bytes = mbrtowc (&wc, p, plimit - p, &mbstate); + + if (bytes == (size_t) -1) + { + /* An invalid multibyte sequence was + encountered. Skip one input byte, and + put a question mark. */ + p++; + *q++ = '?'; + break; + } + + if (bytes == (size_t) -2) + { + /* An incomplete multibyte character + at the end. Replace it entirely with + a question mark. */ + p = plimit; + *q++ = '?'; + break; + } + + if (bytes == 0) + /* A null wide character was encountered. */ + bytes = 1; + + w = wcwidth (wc); + if (w >= 0) + { + /* A printable multibyte character. + Keep it. */ + for (; bytes > 0; --bytes) + *q++ = *p++; + } + else + { + /* An unprintable multibyte character. + Replace it entirely with a question + mark. */ + p += bytes; + *q++ = '?'; + } + } + while (! mbsinit (&mbstate)); + } + break; + } + + /* The buffer may have shrunk. */ + len = q - buf; + return len; + } +} +#endif + + +/* Scan BUF, replacing any dangerous-looking characters with question + * marks. This code is taken from the ls.c file in coreutils as at + * Sun Jun 5 20:51:54 2005 UTC. + * + * This function may shrink the buffer. Either way, the new length + * is returned. + */ +size_t +qmark_chars(char *buf, size_t len) +{ +#if HAVE_MBRTOWC + return multibyte_qmark_chars(buf, len); +#else + return unibyte_qmark_chars(buf, len); +#endif +} + diff --git a/src/bin/findutils/lib/regex.c b/src/bin/findutils/lib/regex.c deleted file mode 100644 index bfc6298a94..0000000000 --- a/src/bin/findutils/lib/regex.c +++ /dev/null @@ -1,5251 +0,0 @@ -/* Extended regular expression matching and search library, - version 0.12. - (Implements POSIX draft P10003.2/D11.2, except for - internationalization features.) - - Copyright (C) 1993, 1994 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -/* AIX requires this to be the first thing in the file. */ -#if defined (_AIX) && !defined (REGEX_MALLOC) - #pragma alloca -#endif - - -/********************************************/ -/* Remove this to enable debugging in regex */ -#undef DEBUG -/********************************************/ - - -#define _GNU_SOURCE - -#ifdef HAVE_CONFIG_H -#include -#endif - -/* We need this for `regex.h', and perhaps for the Emacs include files. */ -#include - -/* The `emacs' switch turns on certain matching commands - that make sense only in Emacs. */ -#ifdef emacs - -#include "lisp.h" -#include "buffer.h" -#include "syntax.h" - -/* Emacs uses `NULL' as a predicate. */ -#undef NULL - -#else /* not emacs */ - -#ifdef STDC_HEADERS -#include -#else -char *malloc (); -char *realloc (); -#endif - - -/* We used to test for `BSTRING' here, but only GCC and Emacs define - `BSTRING', as far as I know, and neither of them use this code. */ -#ifndef INHIBIT_STRING_HEADER -#if HAVE_STRING_H || STDC_HEADERS -#include -#ifndef bcmp -#define bcmp(s1, s2, n) memcmp ((s1), (s2), (n)) -#endif -#ifndef bcopy -#define bcopy(s, d, n) memcpy ((d), (s), (n)) -#endif -#ifndef bzero -#define bzero(s, n) memset ((s), 0, (n)) -#endif -#else -#include -#endif -#endif - -/* Define the syntax stuff for \<, \>, etc. */ - -/* This must be nonzero for the wordchar and notwordchar pattern - commands in re_match_2. */ -#ifndef Sword -#define Sword 1 -#endif - -#ifdef SYNTAX_TABLE - -extern char *re_syntax_table; - -#else /* not SYNTAX_TABLE */ - -/* How many characters in the character set. */ -#define CHAR_SET_SIZE 256 - -static char re_syntax_table[CHAR_SET_SIZE]; - -static void -init_syntax_once () -{ - register int c; - static int done = 0; - - if (done) - return; - - bzero (re_syntax_table, sizeof re_syntax_table); - - for (c = 'a'; c <= 'z'; c++) - re_syntax_table[c] = Sword; - - for (c = 'A'; c <= 'Z'; c++) - re_syntax_table[c] = Sword; - - for (c = '0'; c <= '9'; c++) - re_syntax_table[c] = Sword; - - re_syntax_table['_'] = Sword; - - done = 1; -} - -#endif /* not SYNTAX_TABLE */ - -#define SYNTAX(c) re_syntax_table[c] - -#endif /* not emacs */ - -/* Get the interface, including the syntax bits. */ -#include "regex.h" - -/* isalpha etc. are used for the character classes. */ -#include - -/* Jim Meyering writes: - - "... Some ctype macros are valid only for character codes that - isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when - using /bin/cc or gcc but without giving an ansi option). So, all - ctype uses should be through macros like ISPRINT... If - STDC_HEADERS is defined, then autoconf has verified that the ctype - macros don't need to be guarded with references to isascii. ... - Defining isascii to 1 should let any compiler worth its salt - eliminate the && through constant folding." */ - -#if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII)) -#define ISASCII(c) 1 -#else -#define ISASCII(c) isascii(c) -#endif - -#ifdef isblank -#define ISBLANK(c) (ISASCII (c) && isblank (c)) -#else -#define ISBLANK(c) ((c) == ' ' || (c) == '\t') -#endif -#ifdef isgraph -#define ISGRAPH(c) (ISASCII (c) && isgraph (c)) -#else -#define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c)) -#endif - -#define ISPRINT(c) (ISASCII (c) && isprint (c)) -#define ISDIGIT(c) (ISASCII (c) && isdigit (c)) -#define ISALNUM(c) (ISASCII (c) && isalnum (c)) -#define ISALPHA(c) (ISASCII (c) && isalpha (c)) -#define ISCNTRL(c) (ISASCII (c) && iscntrl (c)) -#define ISLOWER(c) (ISASCII (c) && islower (c)) -#define ISPUNCT(c) (ISASCII (c) && ispunct (c)) -#define ISSPACE(c) (ISASCII (c) && isspace (c)) -#define ISUPPER(c) (ISASCII (c) && isupper (c)) -#define ISXDIGIT(c) (ISASCII (c) && isxdigit (c)) - -#ifndef NULL -#define NULL 0 -#endif - -/* We remove any previous definition of `SIGN_EXTEND_CHAR', - since ours (we hope) works properly with all combinations of - machines, compilers, `char' and `unsigned char' argument types. - (Per Bothner suggested the basic approach.) */ -#undef SIGN_EXTEND_CHAR -#if __STDC__ -#define SIGN_EXTEND_CHAR(c) ((signed char) (c)) -#else /* not __STDC__ */ -/* As in Harbison and Steele. */ -#define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128) -#endif - -/* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we - use `alloca' instead of `malloc'. This is because using malloc in - re_search* or re_match* could cause memory leaks when C-g is used in - Emacs; also, malloc is slower and causes storage fragmentation. On - the other hand, malloc is more portable, and easier to debug. - - Because we sometimes use alloca, some routines have to be macros, - not functions -- `alloca'-allocated space disappears at the end of the - function it is called in. */ - -#ifdef REGEX_MALLOC - -#define REGEX_ALLOCATE malloc -#define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize) - -#else /* not REGEX_MALLOC */ - -/* Emacs already defines alloca, sometimes. */ -#ifndef alloca - -/* Make alloca work the best possible way. */ -#ifdef __GNUC__ -#define alloca __builtin_alloca -#else /* not __GNUC__ */ -#if HAVE_ALLOCA_H -#include -#else /* not __GNUC__ or HAVE_ALLOCA_H */ -#ifndef _AIX /* Already did AIX, up at the top. */ -char *alloca (); -#endif /* not _AIX */ -#endif /* not HAVE_ALLOCA_H */ -#endif /* not __GNUC__ */ - -#endif /* not alloca */ - -#define REGEX_ALLOCATE alloca - -/* Assumes a `char *destination' variable. */ -#define REGEX_REALLOCATE(source, osize, nsize) \ - (destination = (char *) alloca (nsize), \ - bcopy (source, destination, osize), \ - destination) - -#endif /* not REGEX_MALLOC */ - - -/* True if `size1' is non-NULL and PTR is pointing anywhere inside - `string1' or just past its end. This works if PTR is NULL, which is - a good thing. */ -#define FIRST_STRING_P(ptr) \ - (size1 && string1 <= (ptr) && (ptr) <= string1 + size1) - -/* (Re)Allocate N items of type T using malloc, or fail. */ -#define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t))) -#define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t))) -#define RETALLOC_IF(addr, n, t) \ - if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t) -#define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t))) - -#define BYTEWIDTH 8 /* In bits. */ - -#define STREQ(s1, s2) ((strcmp (s1, s2) == 0)) - -#undef MAX -#undef MIN -#define MAX(a, b) ((a) > (b) ? (a) : (b)) -#define MIN(a, b) ((a) < (b) ? (a) : (b)) - -typedef char boolean; -#define false 0 -#define true 1 - -static int re_match_2_internal (); - -/* These are the command codes that appear in compiled regular - expressions. Some opcodes are followed by argument bytes. A - command code can specify any interpretation whatsoever for its - arguments. Zero bytes may appear in the compiled regular expression. */ - -typedef enum -{ - no_op = 0, - - /* Followed by one byte giving n, then by n literal bytes. */ - exactn, - - /* Matches any (more or less) character. */ - anychar, - - /* Matches any one char belonging to specified set. First - following byte is number of bitmap bytes. Then come bytes - for a bitmap saying which chars are in. Bits in each byte - are ordered low-bit-first. A character is in the set if its - bit is 1. A character too large to have a bit in the map is - automatically not in the set. */ - charset, - - /* Same parameters as charset, but match any character that is - not one of those specified. */ - charset_not, - - /* Start remembering the text that is matched, for storing in a - register. Followed by one byte with the register number, in - the range 0 to one less than the pattern buffer's re_nsub - field. Then followed by one byte with the number of groups - inner to this one. (This last has to be part of the - start_memory only because we need it in the on_failure_jump - of re_match_2.) */ - start_memory, - - /* Stop remembering the text that is matched and store it in a - memory register. Followed by one byte with the register - number, in the range 0 to one less than `re_nsub' in the - pattern buffer, and one byte with the number of inner groups, - just like `start_memory'. (We need the number of inner - groups here because we don't have any easy way of finding the - corresponding start_memory when we're at a stop_memory.) */ - stop_memory, - - /* Match a duplicate of something remembered. Followed by one - byte containing the register number. */ - duplicate, - - /* Fail unless at beginning of line. */ - begline, - - /* Fail unless at end of line. */ - endline, - - /* Succeeds if at beginning of buffer (if emacs) or at beginning - of string to be matched (if not). */ - begbuf, - - /* Analogously, for end of buffer/string. */ - endbuf, - - /* Followed by two byte relative address to which to jump. */ - jump, - - /* Same as jump, but marks the end of an alternative. */ - jump_past_alt, - - /* Followed by two-byte relative address of place to resume at - in case of failure. */ - on_failure_jump, - - /* Like on_failure_jump, but pushes a placeholder instead of the - current string position when executed. */ - on_failure_keep_string_jump, - - /* Throw away latest failure point and then jump to following - two-byte relative address. */ - pop_failure_jump, - - /* Change to pop_failure_jump if know won't have to backtrack to - match; otherwise change to jump. This is used to jump - back to the beginning of a repeat. If what follows this jump - clearly won't match what the repeat does, such that we can be - sure that there is no use backtracking out of repetitions - already matched, then we change it to a pop_failure_jump. - Followed by two-byte address. */ - maybe_pop_jump, - - /* Jump to following two-byte address, and push a dummy failure - point. This failure point will be thrown away if an attempt - is made to use it for a failure. A `+' construct makes this - before the first repeat. Also used as an intermediary kind - of jump when compiling an alternative. */ - dummy_failure_jump, - - /* Push a dummy failure point and continue. Used at the end of - alternatives. */ - push_dummy_failure, - - /* Followed by two-byte relative address and two-byte number n. - After matching N times, jump to the address upon failure. */ - succeed_n, - - /* Followed by two-byte relative address, and two-byte number n. - Jump to the address N times, then fail. */ - jump_n, - - /* Set the following two-byte relative address to the - subsequent two-byte number. The address *includes* the two - bytes of number. */ - set_number_at, - - wordchar, /* Matches any word-constituent character. */ - notwordchar, /* Matches any char that is not a word-constituent. */ - - wordbeg, /* Succeeds if at word beginning. */ - wordend, /* Succeeds if at word end. */ - - wordbound, /* Succeeds if at a word boundary. */ - notwordbound /* Succeeds if not at a word boundary. */ - -#ifdef emacs - ,before_dot, /* Succeeds if before point. */ - at_dot, /* Succeeds if at point. */ - after_dot, /* Succeeds if after point. */ - - /* Matches any character whose syntax is specified. Followed by - a byte which contains a syntax code, e.g., Sword. */ - syntaxspec, - - /* Matches any character whose syntax is not that specified. */ - notsyntaxspec -#endif /* emacs */ -} re_opcode_t; - -/* Common operations on the compiled pattern. */ - -/* Store NUMBER in two contiguous bytes starting at DESTINATION. */ - -#define STORE_NUMBER(destination, number) \ - do { \ - (destination)[0] = (number) & 0377; \ - (destination)[1] = (number) >> 8; \ - } while (0) - -/* Same as STORE_NUMBER, except increment DESTINATION to - the byte after where the number is stored. Therefore, DESTINATION - must be an lvalue. */ - -#define STORE_NUMBER_AND_INCR(destination, number) \ - do { \ - STORE_NUMBER (destination, number); \ - (destination) += 2; \ - } while (0) - -/* Put into DESTINATION a number stored in two contiguous bytes starting - at SOURCE. */ - -#define EXTRACT_NUMBER(destination, source) \ - do { \ - (destination) = *(source) & 0377; \ - (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \ - } while (0) - -#ifdef DEBUG -static void -extract_number (dest, source) - int *dest; - unsigned char *source; -{ - int temp = SIGN_EXTEND_CHAR (*(source + 1)); - *dest = *source & 0377; - *dest += temp << 8; -} - -#ifndef EXTRACT_MACROS /* To debug the macros. */ -#undef EXTRACT_NUMBER -#define EXTRACT_NUMBER(dest, src) extract_number (&dest, src) -#endif /* not EXTRACT_MACROS */ - -#endif /* DEBUG */ - -/* Same as EXTRACT_NUMBER, except increment SOURCE to after the number. - SOURCE must be an lvalue. */ - -#define EXTRACT_NUMBER_AND_INCR(destination, source) \ - do { \ - EXTRACT_NUMBER (destination, source); \ - (source) += 2; \ - } while (0) - -#ifdef DEBUG -static void -extract_number_and_incr (destination, source) - int *destination; - unsigned char **source; -{ - extract_number (destination, *source); - *source += 2; -} - -#ifndef EXTRACT_MACROS -#undef EXTRACT_NUMBER_AND_INCR -#define EXTRACT_NUMBER_AND_INCR(dest, src) \ - extract_number_and_incr (&dest, &src) -#endif /* not EXTRACT_MACROS */ - -#endif /* DEBUG */ - -/* If DEBUG is defined, Regex prints many voluminous messages about what - it is doing (if the variable `debug' is nonzero). If linked with the - main program in `iregex.c', you can enter patterns and strings - interactively. And if linked with the main program in `main.c' and - the other test files, you can run the already-written tests. */ - -#ifdef DEBUG - -/* We use standard I/O for debugging. */ -#include - -/* It is useful to test things that ``must'' be true when debugging. */ -#include - -static int debug = 0; - -#define DEBUG_STATEMENT(e) e -#define DEBUG_PRINT1(x) if (debug) printf (x) -#define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2) -#define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3) -#define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4) -#define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \ - if (debug) print_partial_compiled_pattern (s, e) -#define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \ - if (debug) print_double_string (w, s1, sz1, s2, sz2) - - -extern void printchar (); - -/* Print the fastmap in human-readable form. */ - -void -print_fastmap (fastmap) - char *fastmap; -{ - unsigned was_a_range = 0; - unsigned i = 0; - - while (i < (1 << BYTEWIDTH)) - { - if (fastmap[i++]) - { - was_a_range = 0; - printchar (i - 1); - while (i < (1 << BYTEWIDTH) && fastmap[i]) - { - was_a_range = 1; - i++; - } - if (was_a_range) - { - printf ("-"); - printchar (i - 1); - } - } - } - putchar ('\n'); -} - - -/* Print a compiled pattern string in human-readable form, starting at - the START pointer into it and ending just before the pointer END. */ - -void -print_partial_compiled_pattern (start, end) - unsigned char *start; - unsigned char *end; -{ - int mcnt, mcnt2; - unsigned char *p = start; - unsigned char *pend = end; - - if (start == NULL) - { - printf ("(null)\n"); - return; - } - - /* Loop over pattern commands. */ - while (p < pend) - { - printf ("%d:\t", p - start); - - switch ((re_opcode_t) *p++) - { - case no_op: - printf ("/no_op"); - break; - - case exactn: - mcnt = *p++; - printf ("/exactn/%d", mcnt); - do - { - putchar ('/'); - printchar (*p++); - } - while (--mcnt); - break; - - case start_memory: - mcnt = *p++; - printf ("/start_memory/%d/%d", mcnt, *p++); - break; - - case stop_memory: - mcnt = *p++; - printf ("/stop_memory/%d/%d", mcnt, *p++); - break; - - case duplicate: - printf ("/duplicate/%d", *p++); - break; - - case anychar: - printf ("/anychar"); - break; - - case charset: - case charset_not: - { - register int c, last = -100; - register int in_range = 0; - - printf ("/charset [%s", - (re_opcode_t) *(p - 1) == charset_not ? "^" : ""); - - assert (p + *p < pend); - - for (c = 0; c < 256; c++) - if (c / 8 < *p - && (p[1 + (c/8)] & (1 << (c % 8)))) - { - /* Are we starting a range? */ - if (last + 1 == c && ! in_range) - { - putchar ('-'); - in_range = 1; - } - /* Have we broken a range? */ - else if (last + 1 != c && in_range) - { - printchar (last); - in_range = 0; - } - - if (! in_range) - printchar (c); - - last = c; - } - - if (in_range) - printchar (last); - - putchar (']'); - - p += 1 + *p; - } - break; - - case begline: - printf ("/begline"); - break; - - case endline: - printf ("/endline"); - break; - - case on_failure_jump: - extract_number_and_incr (&mcnt, &p); - printf ("/on_failure_jump to %d", p + mcnt - start); - break; - - case on_failure_keep_string_jump: - extract_number_and_incr (&mcnt, &p); - printf ("/on_failure_keep_string_jump to %d", p + mcnt - start); - break; - - case dummy_failure_jump: - extract_number_and_incr (&mcnt, &p); - printf ("/dummy_failure_jump to %d", p + mcnt - start); - break; - - case push_dummy_failure: - printf ("/push_dummy_failure"); - break; - - case maybe_pop_jump: - extract_number_and_incr (&mcnt, &p); - printf ("/maybe_pop_jump to %d", p + mcnt - start); - break; - - case pop_failure_jump: - extract_number_and_incr (&mcnt, &p); - printf ("/pop_failure_jump to %d", p + mcnt - start); - break; - - case jump_past_alt: - extract_number_and_incr (&mcnt, &p); - printf ("/jump_past_alt to %d", p + mcnt - start); - break; - - case jump: - extract_number_and_incr (&mcnt, &p); - printf ("/jump to %d", p + mcnt - start); - break; - - case succeed_n: - extract_number_and_incr (&mcnt, &p); - extract_number_and_incr (&mcnt2, &p); - printf ("/succeed_n to %d, %d times", p + mcnt - start, mcnt2); - break; - - case jump_n: - extract_number_and_incr (&mcnt, &p); - extract_number_and_incr (&mcnt2, &p); - printf ("/jump_n to %d, %d times", p + mcnt - start, mcnt2); - break; - - case set_number_at: - extract_number_and_incr (&mcnt, &p); - extract_number_and_incr (&mcnt2, &p); - printf ("/set_number_at location %d to %d", p + mcnt - start, mcnt2); - break; - - case wordbound: - printf ("/wordbound"); - break; - - case notwordbound: - printf ("/notwordbound"); - break; - - case wordbeg: - printf ("/wordbeg"); - break; - - case wordend: - printf ("/wordend"); - -#ifdef emacs - case before_dot: - printf ("/before_dot"); - break; - - case at_dot: - printf ("/at_dot"); - break; - - case after_dot: - printf ("/after_dot"); - break; - - case syntaxspec: - printf ("/syntaxspec"); - mcnt = *p++; - printf ("/%d", mcnt); - break; - - case notsyntaxspec: - printf ("/notsyntaxspec"); - mcnt = *p++; - printf ("/%d", mcnt); - break; -#endif /* emacs */ - - case wordchar: - printf ("/wordchar"); - break; - - case notwordchar: - printf ("/notwordchar"); - break; - - case begbuf: - printf ("/begbuf"); - break; - - case endbuf: - printf ("/endbuf"); - break; - - default: - printf ("?%d", *(p-1)); - } - - putchar ('\n'); - } - - printf ("%d:\tend of pattern.\n", p - start); -} - - -void -print_compiled_pattern (bufp) - struct re_pattern_buffer *bufp; -{ - unsigned char *buffer = bufp->buffer; - - print_partial_compiled_pattern (buffer, buffer + bufp->used); - printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated); - - if (bufp->fastmap_accurate && bufp->fastmap) - { - printf ("fastmap: "); - print_fastmap (bufp->fastmap); - } - - printf ("re_nsub: %d\t", bufp->re_nsub); - printf ("regs_alloc: %d\t", bufp->regs_allocated); - printf ("can_be_null: %d\t", bufp->can_be_null); - printf ("newline_anchor: %d\n", bufp->newline_anchor); - printf ("no_sub: %d\t", bufp->no_sub); - printf ("not_bol: %d\t", bufp->not_bol); - printf ("not_eol: %d\t", bufp->not_eol); - printf ("syntax: %d\n", bufp->syntax); - /* Perhaps we should print the translate table? */ -} - - -void -print_double_string (where, string1, size1, string2, size2) - const char *where; - const char *string1; - const char *string2; - int size1; - int size2; -{ - unsigned this_char; - - if (where == NULL) - printf ("(null)"); - else - { - if (FIRST_STRING_P (where)) - { - for (this_char = where - string1; this_char < size1; this_char++) - printchar (string1[this_char]); - - where = string2; - } - - for (this_char = where - string2; this_char < size2; this_char++) - printchar (string2[this_char]); - } -} - -#else /* not DEBUG */ - -#undef assert -#define assert(e) - -#define DEBUG_STATEMENT(e) -#define DEBUG_PRINT1(x) -#define DEBUG_PRINT2(x1, x2) -#define DEBUG_PRINT3(x1, x2, x3) -#define DEBUG_PRINT4(x1, x2, x3, x4) -#define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) -#define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) - -#endif /* not DEBUG */ - -/* Set by `re_set_syntax' to the current regexp syntax to recognize. Can - also be assigned to arbitrarily: each pattern buffer stores its own - syntax, so it can be changed between regex compilations. */ -reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS; - - -/* Specify the precise syntax of regexps for compilation. This provides - for compatibility for various utilities which historically have - different, incompatible syntaxes. - - The argument SYNTAX is a bit mask comprised of the various bits - defined in regex.h. We return the old syntax. */ - -reg_syntax_t -re_set_syntax (syntax) - reg_syntax_t syntax; -{ - reg_syntax_t ret = re_syntax_options; - - re_syntax_options = syntax; - return ret; -} - -/* This table gives an error message for each of the error codes listed - in regex.h. Obviously the order here has to be same as there. */ - -static const char *re_error_msg[] = - { NULL, /* REG_NOERROR */ - "No match", /* REG_NOMATCH */ - "Invalid regular expression", /* REG_BADPAT */ - "Invalid collation character", /* REG_ECOLLATE */ - "Invalid character class name", /* REG_ECTYPE */ - "Trailing backslash", /* REG_EESCAPE */ - "Invalid back reference", /* REG_ESUBREG */ - "Unmatched [ or [^", /* REG_EBRACK */ - "Unmatched ( or \\(", /* REG_EPAREN */ - "Unmatched \\{", /* REG_EBRACE */ - "Invalid content of \\{\\}", /* REG_BADBR */ - "Invalid range end", /* REG_ERANGE */ - "Memory exhausted", /* REG_ESPACE */ - "Invalid preceding regular expression", /* REG_BADRPT */ - "Premature end of regular expression", /* REG_EEND */ - "Regular expression too big", /* REG_ESIZE */ - "Unmatched ) or \\)", /* REG_ERPAREN */ - }; - -/* Avoiding alloca during matching, to placate r_alloc. */ - -/* Define MATCH_MAY_ALLOCATE unless we need to make sure that the - searching and matching functions should not call alloca. On some - systems, alloca is implemented in terms of malloc, and if we're - using the relocating allocator routines, then malloc could cause a - relocation, which might (if the strings being searched are in the - ralloc heap) shift the data out from underneath the regexp - routines. - - Here's another reason to avoid allocation: Emacs - processes input from X in a signal handler; processing X input may - call malloc; if input arrives while a matching routine is calling - malloc, then we're scrod. But Emacs can't just block input while - calling matching routines; then we don't notice interrupts when - they come in. So, Emacs blocks input around all regexp calls - except the matching calls, which it leaves unprotected, in the - faith that they will not malloc. */ - -/* Normally, this is fine. */ -#define MATCH_MAY_ALLOCATE - -/* The match routines may not allocate if (1) they would do it with malloc - and (2) it's not safe for them to use malloc. */ -#if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && (defined (emacs) || defined (REL_ALLOC)) -#undef MATCH_MAY_ALLOCATE -#endif - - -/* Failure stack declarations and macros; both re_compile_fastmap and - re_match_2 use a failure stack. These have to be macros because of - REGEX_ALLOCATE. */ - - -/* Number of failure points for which to initially allocate space - when matching. If this number is exceeded, we allocate more - space, so it is not a hard limit. */ -#ifndef INIT_FAILURE_ALLOC -#define INIT_FAILURE_ALLOC 5 -#endif - -/* Roughly the maximum number of failure points on the stack. Would be - exactly that if always used MAX_FAILURE_SPACE each time we failed. - This is a variable only so users of regex can assign to it; we never - change it ourselves. */ -int re_max_failures = 2000; - -typedef unsigned char *fail_stack_elt_t; - -typedef struct -{ - fail_stack_elt_t *stack; - unsigned size; - unsigned avail; /* Offset of next open position. */ -} fail_stack_type; - -#define FAIL_STACK_EMPTY() (fail_stack.avail == 0) -#define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0) -#define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size) -#define FAIL_STACK_TOP() (fail_stack.stack[fail_stack.avail]) - - -/* Initialize `fail_stack'. Do `return -2' if the alloc fails. */ - -#ifdef MATCH_MAY_ALLOCATE -#define INIT_FAIL_STACK() \ - do { \ - fail_stack.stack = (fail_stack_elt_t *) \ - REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \ - \ - if (fail_stack.stack == NULL) \ - return -2; \ - \ - fail_stack.size = INIT_FAILURE_ALLOC; \ - fail_stack.avail = 0; \ - } while (0) -#else -#define INIT_FAIL_STACK() \ - do { \ - fail_stack.avail = 0; \ - } while (0) -#endif - - -/* Double the size of FAIL_STACK, up to approximately `re_max_failures' items. - - Return 1 if succeeds, and 0 if either ran out of memory - allocating space for it or it was already too large. - - REGEX_REALLOCATE requires `destination' be declared. */ - -#define DOUBLE_FAIL_STACK(fail_stack) \ - ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \ - ? 0 \ - : ((fail_stack).stack = (fail_stack_elt_t *) \ - REGEX_REALLOCATE ((fail_stack).stack, \ - (fail_stack).size * sizeof (fail_stack_elt_t), \ - ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \ - \ - (fail_stack).stack == NULL \ - ? 0 \ - : ((fail_stack).size <<= 1, \ - 1))) - - -/* Push PATTERN_OP on FAIL_STACK. - - Return 1 if was able to do so and 0 if ran out of memory allocating - space to do so. */ -#define PUSH_PATTERN_OP(pattern_op, fail_stack) \ - ((FAIL_STACK_FULL () \ - && !DOUBLE_FAIL_STACK (fail_stack)) \ - ? 0 \ - : ((fail_stack).stack[(fail_stack).avail++] = pattern_op, \ - 1)) - -/* This pushes an item onto the failure stack. Must be a four-byte - value. Assumes the variable `fail_stack'. Probably should only - be called from within `PUSH_FAILURE_POINT'. */ -#define PUSH_FAILURE_ITEM(item) \ - fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item - -/* The complement operation. Assumes `fail_stack' is nonempty. */ -#define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail] - -/* Used to omit pushing failure point id's when we're not debugging. */ -#ifdef DEBUG -#define DEBUG_PUSH PUSH_FAILURE_ITEM -#define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM () -#else -#define DEBUG_PUSH(item) -#define DEBUG_POP(item_addr) -#endif - - -/* Push the information about the state we will need - if we ever fail back to it. - - Requires variables fail_stack, regstart, regend, reg_info, and - num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be - declared. - - Does `return FAILURE_CODE' if runs out of memory. */ - -#define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \ - do { \ - char *destination; \ - /* Must be int, so when we don't save any registers, the arithmetic \ - of 0 + -1 isn't done as unsigned. */ \ - int this_reg; \ - \ - DEBUG_STATEMENT (failure_id++); \ - DEBUG_STATEMENT (nfailure_points_pushed++); \ - DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \ - DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\ - DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\ - \ - DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \ - DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \ - \ - /* Ensure we have enough space allocated for what we will push. */ \ - while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \ - { \ - if (!DOUBLE_FAIL_STACK (fail_stack)) \ - return failure_code; \ - \ - DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \ - (fail_stack).size); \ - DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\ - } \ - \ - /* Push the info, starting with the registers. */ \ - DEBUG_PRINT1 ("\n"); \ - \ - for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \ - this_reg++) \ - { \ - DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \ - DEBUG_STATEMENT (num_regs_pushed++); \ - \ - DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \ - PUSH_FAILURE_ITEM (regstart[this_reg]); \ - \ - DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \ - PUSH_FAILURE_ITEM (regend[this_reg]); \ - \ - DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \ - DEBUG_PRINT2 (" match_null=%d", \ - REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \ - DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \ - DEBUG_PRINT2 (" matched_something=%d", \ - MATCHED_SOMETHING (reg_info[this_reg])); \ - DEBUG_PRINT2 (" ever_matched=%d", \ - EVER_MATCHED_SOMETHING (reg_info[this_reg])); \ - DEBUG_PRINT1 ("\n"); \ - PUSH_FAILURE_ITEM (reg_info[this_reg].word); \ - } \ - \ - DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\ - PUSH_FAILURE_ITEM (lowest_active_reg); \ - \ - DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\ - PUSH_FAILURE_ITEM (highest_active_reg); \ - \ - DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \ - DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \ - PUSH_FAILURE_ITEM (pattern_place); \ - \ - DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \ - DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \ - size2); \ - DEBUG_PRINT1 ("'\n"); \ - PUSH_FAILURE_ITEM (string_place); \ - \ - DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \ - DEBUG_PUSH (failure_id); \ - } while (0) - -/* This is the number of items that are pushed and popped on the stack - for each register. */ -#define NUM_REG_ITEMS 3 - -/* Individual items aside from the registers. */ -#ifdef DEBUG -#define NUM_NONREG_ITEMS 5 /* Includes failure point id. */ -#else -#define NUM_NONREG_ITEMS 4 -#endif - -/* We push at most this many items on the stack. */ -#define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS) - -/* We actually push this many items. */ -#define NUM_FAILURE_ITEMS \ - ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \ - + NUM_NONREG_ITEMS) - -/* How many items can still be added to the stack without overflowing it. */ -#define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail) - - -/* Pops what PUSH_FAIL_STACK pushes. - - We restore into the parameters, all of which should be lvalues: - STR -- the saved data position. - PAT -- the saved pattern position. - LOW_REG, HIGH_REG -- the highest and lowest active registers. - REGSTART, REGEND -- arrays of string positions. - REG_INFO -- array of information about each subexpression. - - Also assumes the variables `fail_stack' and (if debugging), `bufp', - `pend', `string1', `size1', `string2', and `size2'. */ - -#define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\ -{ \ - DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \ - int this_reg; \ - const unsigned char *string_temp; \ - \ - assert (!FAIL_STACK_EMPTY ()); \ - \ - /* Remove failure points and point to how many regs pushed. */ \ - DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \ - DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \ - DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \ - \ - assert (fail_stack.avail >= NUM_NONREG_ITEMS); \ - \ - DEBUG_POP (&failure_id); \ - DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \ - \ - /* If the saved string location is NULL, it came from an \ - on_failure_keep_string_jump opcode, and we want to throw away the \ - saved NULL, thus retaining our current position in the string. */ \ - string_temp = POP_FAILURE_ITEM (); \ - if (string_temp != NULL) \ - str = (const char *) string_temp; \ - \ - DEBUG_PRINT2 (" Popping string 0x%x: `", str); \ - DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \ - DEBUG_PRINT1 ("'\n"); \ - \ - pat = (unsigned char *) POP_FAILURE_ITEM (); \ - DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \ - DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \ - \ - /* Restore register info. */ \ - high_reg = (unsigned) POP_FAILURE_ITEM (); \ - DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \ - \ - low_reg = (unsigned) POP_FAILURE_ITEM (); \ - DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \ - \ - for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \ - { \ - DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \ - \ - reg_info[this_reg].word = POP_FAILURE_ITEM (); \ - DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \ - \ - regend[this_reg] = (const char *) POP_FAILURE_ITEM (); \ - DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \ - \ - regstart[this_reg] = (const char *) POP_FAILURE_ITEM (); \ - DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \ - } \ - \ - DEBUG_STATEMENT (nfailure_points_popped++); \ -} /* POP_FAILURE_POINT */ - - - -/* Structure for per-register (a.k.a. per-group) information. - This must not be longer than one word, because we push this value - onto the failure stack. Other register information, such as the - starting and ending positions (which are addresses), and the list of - inner groups (which is a bits list) are maintained in separate - variables. - - We are making a (strictly speaking) nonportable assumption here: that - the compiler will pack our bit fields into something that fits into - the type of `word', i.e., is something that fits into one item on the - failure stack. */ -typedef union -{ - fail_stack_elt_t word; - struct - { - /* This field is one if this group can match the empty string, - zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */ -#define MATCH_NULL_UNSET_VALUE 3 - unsigned match_null_string_p : 2; - unsigned is_active : 1; - unsigned matched_something : 1; - unsigned ever_matched_something : 1; - } bits; -} register_info_type; - -#define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p) -#define IS_ACTIVE(R) ((R).bits.is_active) -#define MATCHED_SOMETHING(R) ((R).bits.matched_something) -#define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something) - - -/* Call this when have matched a real character; it sets `matched' flags - for the subexpressions which we are currently inside. Also records - that those subexprs have matched. */ -#define SET_REGS_MATCHED() \ - do \ - { \ - unsigned r; \ - for (r = lowest_active_reg; r <= highest_active_reg; r++) \ - { \ - MATCHED_SOMETHING (reg_info[r]) \ - = EVER_MATCHED_SOMETHING (reg_info[r]) \ - = 1; \ - } \ - } \ - while (0) - - -/* Registers are set to a sentinel when they haven't yet matched. */ -#define REG_UNSET_VALUE ((char *) -1) -#define REG_UNSET(e) ((e) == REG_UNSET_VALUE) - - - -/* How do we implement a missing MATCH_MAY_ALLOCATE? - We make the fail stack a global thing, and then grow it to - re_max_failures when we compile. */ -#ifndef MATCH_MAY_ALLOCATE -static fail_stack_type fail_stack; - -static const char ** regstart, ** regend; -static const char ** old_regstart, ** old_regend; -static const char **best_regstart, **best_regend; -static register_info_type *reg_info; -static const char **reg_dummy; -static register_info_type *reg_info_dummy; -#endif - - -/* Subroutine declarations and macros for regex_compile. */ - -static void store_op1 (), store_op2 (); -static void insert_op1 (), insert_op2 (); -static boolean at_begline_loc_p (), at_endline_loc_p (); -static boolean group_in_compile_stack (); -static reg_errcode_t compile_range (); - -/* Fetch the next character in the uncompiled pattern---translating it - if necessary. Also cast from a signed character in the constant - string passed to us by the user to an unsigned char that we can use - as an array index (in, e.g., `translate'). */ -#define PATFETCH(c) \ - do {if (p == pend) return REG_EEND; \ - c = (unsigned char) *p++; \ - if (translate) c = translate[c]; \ - } while (0) - -/* Fetch the next character in the uncompiled pattern, with no - translation. */ -#define PATFETCH_RAW(c) \ - do {if (p == pend) return REG_EEND; \ - c = (unsigned char) *p++; \ - } while (0) - -/* Go backwards one character in the pattern. */ -#define PATUNFETCH p-- - - -/* If `translate' is non-null, return translate[D], else just D. We - cast the subscript to translate because some data is declared as - `char *', to avoid warnings when a string constant is passed. But - when we use a character as a subscript we must make it unsigned. */ -#define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d)) - - -/* Macros for outputting the compiled pattern into `buffer'. */ - -/* If the buffer isn't allocated when it comes in, use this. */ -#define INIT_BUF_SIZE 32 - -/* Make sure we have at least N more bytes of space in buffer. */ -#define GET_BUFFER_SPACE(n) \ - while (b - bufp->buffer + (n) > bufp->allocated) \ - EXTEND_BUFFER () - -/* Make sure we have one more byte of buffer space and then add C to it. */ -#define BUF_PUSH(c) \ - do { \ - GET_BUFFER_SPACE (1); \ - *b++ = (unsigned char) (c); \ - } while (0) - - -/* Ensure we have two more bytes of buffer space and then append C1 and C2. */ -#define BUF_PUSH_2(c1, c2) \ - do { \ - GET_BUFFER_SPACE (2); \ - *b++ = (unsigned char) (c1); \ - *b++ = (unsigned char) (c2); \ - } while (0) - - -/* As with BUF_PUSH_2, except for three bytes. */ -#define BUF_PUSH_3(c1, c2, c3) \ - do { \ - GET_BUFFER_SPACE (3); \ - *b++ = (unsigned char) (c1); \ - *b++ = (unsigned char) (c2); \ - *b++ = (unsigned char) (c3); \ - } while (0) - - -/* Store a jump with opcode OP at LOC to location TO. We store a - relative address offset by the three bytes the jump itself occupies. */ -#define STORE_JUMP(op, loc, to) \ - store_op1 (op, loc, (to) - (loc) - 3) - -/* Likewise, for a two-argument jump. */ -#define STORE_JUMP2(op, loc, to, arg) \ - store_op2 (op, loc, (to) - (loc) - 3, arg) - -/* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */ -#define INSERT_JUMP(op, loc, to) \ - insert_op1 (op, loc, (to) - (loc) - 3, b) - -/* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */ -#define INSERT_JUMP2(op, loc, to, arg) \ - insert_op2 (op, loc, (to) - (loc) - 3, arg, b) - - -/* This is not an arbitrary limit: the arguments which represent offsets - into the pattern are two bytes long. So if 2^16 bytes turns out to - be too small, many things would have to change. */ -#define MAX_BUF_SIZE (1L << 16) - - -/* Extend the buffer by twice its current size via realloc and - reset the pointers that pointed into the old block to point to the - correct places in the new one. If extending the buffer results in it - being larger than MAX_BUF_SIZE, then flag memory exhausted. */ -#define EXTEND_BUFFER() \ - do { \ - unsigned char *old_buffer = bufp->buffer; \ - if (bufp->allocated == MAX_BUF_SIZE) \ - return REG_ESIZE; \ - bufp->allocated <<= 1; \ - if (bufp->allocated > MAX_BUF_SIZE) \ - bufp->allocated = MAX_BUF_SIZE; \ - bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\ - if (bufp->buffer == NULL) \ - return REG_ESPACE; \ - /* If the buffer moved, move all the pointers into it. */ \ - if (old_buffer != bufp->buffer) \ - { \ - b = (b - old_buffer) + bufp->buffer; \ - begalt = (begalt - old_buffer) + bufp->buffer; \ - if (fixup_alt_jump) \ - fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\ - if (laststart) \ - laststart = (laststart - old_buffer) + bufp->buffer; \ - if (pending_exact) \ - pending_exact = (pending_exact - old_buffer) + bufp->buffer; \ - } \ - } while (0) - - -/* Since we have one byte reserved for the register number argument to - {start,stop}_memory, the maximum number of groups we can report - things about is what fits in that byte. */ -#define MAX_REGNUM 255 - -/* But patterns can have more than `MAX_REGNUM' registers. We just - ignore the excess. */ -typedef unsigned regnum_t; - - -/* Macros for the compile stack. */ - -/* Since offsets can go either forwards or backwards, this type needs to - be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */ -typedef int pattern_offset_t; - -typedef struct -{ - pattern_offset_t begalt_offset; - pattern_offset_t fixup_alt_jump; - pattern_offset_t inner_group_offset; - pattern_offset_t laststart_offset; - regnum_t regnum; -} compile_stack_elt_t; - - -typedef struct -{ - compile_stack_elt_t *stack; - unsigned size; - unsigned avail; /* Offset of next open position. */ -} compile_stack_type; - - -#define INIT_COMPILE_STACK_SIZE 32 - -#define COMPILE_STACK_EMPTY (compile_stack.avail == 0) -#define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size) - -/* The next available element. */ -#define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail]) - - -/* Set the bit for character C in a list. */ -#define SET_LIST_BIT(c) \ - (b[((unsigned char) (c)) / BYTEWIDTH] \ - |= 1 << (((unsigned char) c) % BYTEWIDTH)) - - -/* Get the next unsigned number in the uncompiled pattern. */ -#define GET_UNSIGNED_NUMBER(num) \ - { if (p != pend) \ - { \ - PATFETCH (c); \ - while (ISDIGIT (c)) \ - { \ - if (num < 0) \ - num = 0; \ - num = num * 10 + c - '0'; \ - if (p == pend) \ - break; \ - PATFETCH (c); \ - } \ - } \ - } - -#define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */ - -#define IS_CHAR_CLASS(string) \ - (STREQ (string, "alpha") || STREQ (string, "upper") \ - || STREQ (string, "lower") || STREQ (string, "digit") \ - || STREQ (string, "alnum") || STREQ (string, "xdigit") \ - || STREQ (string, "space") || STREQ (string, "print") \ - || STREQ (string, "punct") || STREQ (string, "graph") \ - || STREQ (string, "cntrl") || STREQ (string, "blank")) - -/* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX. - Returns one of error codes defined in `regex.h', or zero for success. - - Assumes the `allocated' (and perhaps `buffer') and `translate' - fields are set in BUFP on entry. - - If it succeeds, results are put in BUFP (if it returns an error, the - contents of BUFP are undefined): - `buffer' is the compiled pattern; - `syntax' is set to SYNTAX; - `used' is set to the length of the compiled pattern; - `fastmap_accurate' is zero; - `re_nsub' is the number of subexpressions in PATTERN; - `not_bol' and `not_eol' are zero; - - The `fastmap' and `newline_anchor' fields are neither - examined nor set. */ - -/* Return, freeing storage we allocated. */ -#define FREE_STACK_RETURN(value) \ - return (free (compile_stack.stack), value) - -static reg_errcode_t -regex_compile (pattern, size, syntax, bufp) - const char *pattern; - int size; - reg_syntax_t syntax; - struct re_pattern_buffer *bufp; -{ - /* We fetch characters from PATTERN here. Even though PATTERN is - `char *' (i.e., signed), we declare these variables as unsigned, so - they can be reliably used as array indices. */ - register unsigned char c, c1; - - /* A random temporary spot in PATTERN. */ - const char *p1; - - /* Points to the end of the buffer, where we should append. */ - register unsigned char *b; - - /* Keeps track of unclosed groups. */ - compile_stack_type compile_stack; - - /* Points to the current (ending) position in the pattern. */ - const char *p = pattern; - const char *pend = pattern + size; - - /* How to translate the characters in the pattern. */ - char *translate = bufp->translate; - - /* Address of the count-byte of the most recently inserted `exactn' - command. This makes it possible to tell if a new exact-match - character can be added to that command or if the character requires - a new `exactn' command. */ - unsigned char *pending_exact = 0; - - /* Address of start of the most recently finished expression. - This tells, e.g., postfix * where to find the start of its - operand. Reset at the beginning of groups and alternatives. */ - unsigned char *laststart = 0; - - /* Address of beginning of regexp, or inside of last group. */ - unsigned char *begalt; - - /* Place in the uncompiled pattern (i.e., the {) to - which to go back if the interval is invalid. */ - const char *beg_interval; - - /* Address of the place where a forward jump should go to the end of - the containing expression. Each alternative of an `or' -- except the - last -- ends with a forward jump of this sort. */ - unsigned char *fixup_alt_jump = 0; - - /* Counts open-groups as they are encountered. Remembered for the - matching close-group on the compile stack, so the same register - number is put in the stop_memory as the start_memory. */ - regnum_t regnum = 0; - -#ifdef DEBUG - DEBUG_PRINT1 ("\nCompiling pattern: "); - if (debug) - { - unsigned debug_count; - - for (debug_count = 0; debug_count < size; debug_count++) - printchar (pattern[debug_count]); - putchar ('\n'); - } -#endif /* DEBUG */ - - /* Initialize the compile stack. */ - compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t); - if (compile_stack.stack == NULL) - return REG_ESPACE; - - compile_stack.size = INIT_COMPILE_STACK_SIZE; - compile_stack.avail = 0; - - /* Initialize the pattern buffer. */ - bufp->syntax = syntax; - bufp->fastmap_accurate = 0; - bufp->not_bol = bufp->not_eol = 0; - - /* Set `used' to zero, so that if we return an error, the pattern - printer (for debugging) will think there's no pattern. We reset it - at the end. */ - bufp->used = 0; - - /* Always count groups, whether or not bufp->no_sub is set. */ - bufp->re_nsub = 0; - -#if !defined (emacs) && !defined (SYNTAX_TABLE) - /* Initialize the syntax table. */ - init_syntax_once (); -#endif - - if (bufp->allocated == 0) - { - if (bufp->buffer) - { /* If zero allocated, but buffer is non-null, try to realloc - enough space. This loses if buffer's address is bogus, but - that is the user's responsibility. */ - RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char); - } - else - { /* Caller did not allocate a buffer. Do it for them. */ - bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char); - } - if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE); - - bufp->allocated = INIT_BUF_SIZE; - } - - begalt = b = bufp->buffer; - - /* Loop through the uncompiled pattern until we're at the end. */ - while (p != pend) - { - PATFETCH (c); - - switch (c) - { - case '^': - { - if ( /* If at start of pattern, it's an operator. */ - p == pattern + 1 - /* If context independent, it's an operator. */ - || syntax & RE_CONTEXT_INDEP_ANCHORS - /* Otherwise, depends on what's come before. */ - || at_begline_loc_p (pattern, p, syntax)) - BUF_PUSH (begline); - else - goto normal_char; - } - break; - - - case '$': - { - if ( /* If at end of pattern, it's an operator. */ - p == pend - /* If context independent, it's an operator. */ - || syntax & RE_CONTEXT_INDEP_ANCHORS - /* Otherwise, depends on what's next. */ - || at_endline_loc_p (p, pend, syntax)) - BUF_PUSH (endline); - else - goto normal_char; - } - break; - - - case '+': - case '?': - if ((syntax & RE_BK_PLUS_QM) - || (syntax & RE_LIMITED_OPS)) - goto normal_char; - handle_plus: - case '*': - /* If there is no previous pattern... */ - if (!laststart) - { - if (syntax & RE_CONTEXT_INVALID_OPS) - FREE_STACK_RETURN (REG_BADRPT); - else if (!(syntax & RE_CONTEXT_INDEP_OPS)) - goto normal_char; - } - - { - /* Are we optimizing this jump? */ - boolean keep_string_p = false; - - /* 1 means zero (many) matches is allowed. */ - char zero_times_ok = 0, many_times_ok = 0; - - /* If there is a sequence of repetition chars, collapse it - down to just one (the right one). We can't combine - interval operators with these because of, e.g., `a{2}*', - which should only match an even number of `a's. */ - - for (;;) - { - zero_times_ok |= c != '+'; - many_times_ok |= c != '?'; - - if (p == pend) - break; - - PATFETCH (c); - - if (c == '*' - || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?'))) - ; - - else if (syntax & RE_BK_PLUS_QM && c == '\\') - { - if (p == pend) FREE_STACK_RETURN (REG_EESCAPE); - - PATFETCH (c1); - if (!(c1 == '+' || c1 == '?')) - { - PATUNFETCH; - PATUNFETCH; - break; - } - - c = c1; - } - else - { - PATUNFETCH; - break; - } - - /* If we get here, we found another repeat character. */ - } - - /* Star, etc. applied to an empty pattern is equivalent - to an empty pattern. */ - if (!laststart) - break; - - /* Now we know whether or not zero matches is allowed - and also whether or not two or more matches is allowed. */ - if (many_times_ok) - { /* More than one repetition is allowed, so put in at the - end a backward relative jump from `b' to before the next - jump we're going to put in below (which jumps from - laststart to after this jump). - - But if we are at the `*' in the exact sequence `.*\n', - insert an unconditional jump backwards to the ., - instead of the beginning of the loop. This way we only - push a failure point once, instead of every time - through the loop. */ - assert (p - 1 > pattern); - - /* Allocate the space for the jump. */ - GET_BUFFER_SPACE (3); - - /* We know we are not at the first character of the pattern, - because laststart was nonzero. And we've already - incremented `p', by the way, to be the character after - the `*'. Do we have to do something analogous here - for null bytes, because of RE_DOT_NOT_NULL? */ - if (TRANSLATE (*(p - 2)) == TRANSLATE ('.') - && zero_times_ok - && p < pend && TRANSLATE (*p) == TRANSLATE ('\n') - && !(syntax & RE_DOT_NEWLINE)) - { /* We have .*\n. */ - STORE_JUMP (jump, b, laststart); - keep_string_p = true; - } - else - /* Anything else. */ - STORE_JUMP (maybe_pop_jump, b, laststart - 3); - - /* We've added more stuff to the buffer. */ - b += 3; - } - - /* On failure, jump from laststart to b + 3, which will be the - end of the buffer after this jump is inserted. */ - GET_BUFFER_SPACE (3); - INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump - : on_failure_jump, - laststart, b + 3); - pending_exact = 0; - b += 3; - - if (!zero_times_ok) - { - /* At least one repetition is required, so insert a - `dummy_failure_jump' before the initial - `on_failure_jump' instruction of the loop. This - effects a skip over that instruction the first time - we hit that loop. */ - GET_BUFFER_SPACE (3); - INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6); - b += 3; - } - } - break; - - - case '.': - laststart = b; - BUF_PUSH (anychar); - break; - - - case '[': - { - boolean had_char_class = false; - - if (p == pend) FREE_STACK_RETURN (REG_EBRACK); - - /* Ensure that we have enough space to push a charset: the - opcode, the length count, and the bitset; 34 bytes in all. */ - GET_BUFFER_SPACE (34); - - laststart = b; - - /* We test `*p == '^' twice, instead of using an if - statement, so we only need one BUF_PUSH. */ - BUF_PUSH (*p == '^' ? charset_not : charset); - if (*p == '^') - p++; - - /* Remember the first position in the bracket expression. */ - p1 = p; - - /* Push the number of bytes in the bitmap. */ - BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH); - - /* Clear the whole map. */ - bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH); - - /* charset_not matches newline according to a syntax bit. */ - if ((re_opcode_t) b[-2] == charset_not - && (syntax & RE_HAT_LISTS_NOT_NEWLINE)) - SET_LIST_BIT ('\n'); - - /* Read in characters and ranges, setting map bits. */ - for (;;) - { - if (p == pend) FREE_STACK_RETURN (REG_EBRACK); - - PATFETCH (c); - - /* \ might escape characters inside [...] and [^...]. */ - if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\') - { - if (p == pend) FREE_STACK_RETURN (REG_EESCAPE); - - PATFETCH (c1); - SET_LIST_BIT (c1); - continue; - } - - /* Could be the end of the bracket expression. If it's - not (i.e., when the bracket expression is `[]' so - far), the ']' character bit gets set way below. */ - if (c == ']' && p != p1 + 1) - break; - - /* Look ahead to see if it's a range when the last thing - was a character class. */ - if (had_char_class && c == '-' && *p != ']') - FREE_STACK_RETURN (REG_ERANGE); - - /* Look ahead to see if it's a range when the last thing - was a character: if this is a hyphen not at the - beginning or the end of a list, then it's the range - operator. */ - if (c == '-' - && !(p - 2 >= pattern && p[-2] == '[') - && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^') - && *p != ']') - { - reg_errcode_t ret - = compile_range (&p, pend, translate, syntax, b); - if (ret != REG_NOERROR) FREE_STACK_RETURN (ret); - } - - else if (p[0] == '-' && p[1] != ']') - { /* This handles ranges made up of characters only. */ - reg_errcode_t ret; - - /* Move past the `-'. */ - PATFETCH (c1); - - ret = compile_range (&p, pend, translate, syntax, b); - if (ret != REG_NOERROR) FREE_STACK_RETURN (ret); - } - - /* See if we're at the beginning of a possible character - class. */ - - else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':') - { /* Leave room for the null. */ - char str[CHAR_CLASS_MAX_LENGTH + 1]; - - PATFETCH (c); - c1 = 0; - - /* If pattern is `[[:'. */ - if (p == pend) FREE_STACK_RETURN (REG_EBRACK); - - for (;;) - { - PATFETCH (c); - if (c == ':' || c == ']' || p == pend - || c1 == CHAR_CLASS_MAX_LENGTH) - break; - str[c1++] = c; - } - str[c1] = '\0'; - - /* If isn't a word bracketed by `[:' and:`]': - undo the ending character, the letters, and leave - the leading `:' and `[' (but set bits for them). */ - if (c == ':' && *p == ']') - { - int ch; - boolean is_alnum = STREQ (str, "alnum"); - boolean is_alpha = STREQ (str, "alpha"); - boolean is_blank = STREQ (str, "blank"); - boolean is_cntrl = STREQ (str, "cntrl"); - boolean is_digit = STREQ (str, "digit"); - boolean is_graph = STREQ (str, "graph"); - boolean is_lower = STREQ (str, "lower"); - boolean is_print = STREQ (str, "print"); - boolean is_punct = STREQ (str, "punct"); - boolean is_space = STREQ (str, "space"); - boolean is_upper = STREQ (str, "upper"); - boolean is_xdigit = STREQ (str, "xdigit"); - - if (!IS_CHAR_CLASS (str)) - FREE_STACK_RETURN (REG_ECTYPE); - - /* Throw away the ] at the end of the character - class. */ - PATFETCH (c); - - if (p == pend) FREE_STACK_RETURN (REG_EBRACK); - - for (ch = 0; ch < 1 << BYTEWIDTH; ch++) - { - /* This was split into 3 if's to - avoid an arbitrary limit in some compiler. */ - if ( (is_alnum && ISALNUM (ch)) - || (is_alpha && ISALPHA (ch)) - || (is_blank && ISBLANK (ch)) - || (is_cntrl && ISCNTRL (ch))) - SET_LIST_BIT (ch); - if ( (is_digit && ISDIGIT (ch)) - || (is_graph && ISGRAPH (ch)) - || (is_lower && ISLOWER (ch)) - || (is_print && ISPRINT (ch))) - SET_LIST_BIT (ch); - if ( (is_punct && ISPUNCT (ch)) - || (is_space && ISSPACE (ch)) - || (is_upper && ISUPPER (ch)) - || (is_xdigit && ISXDIGIT (ch))) - SET_LIST_BIT (ch); - } - had_char_class = true; - } - else - { - c1++; - while (c1--) - PATUNFETCH; - SET_LIST_BIT ('['); - SET_LIST_BIT (':'); - had_char_class = false; - } - } - else - { - had_char_class = false; - SET_LIST_BIT (c); - } - } - - /* Discard any (non)matching list bytes that are all 0 at the - end of the map. Decrease the map-length byte too. */ - while ((int) b[-1] > 0 && b[b[-1] - 1] == 0) - b[-1]--; - b += b[-1]; - } - break; - - - case '(': - if (syntax & RE_NO_BK_PARENS) - goto handle_open; - else - goto normal_char; - - - case ')': - if (syntax & RE_NO_BK_PARENS) - goto handle_close; - else - goto normal_char; - - - case '\n': - if (syntax & RE_NEWLINE_ALT) - goto handle_alt; - else - goto normal_char; - - - case '|': - if (syntax & RE_NO_BK_VBAR) - goto handle_alt; - else - goto normal_char; - - - case '{': - if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES) - goto handle_interval; - else - goto normal_char; - - - case '\\': - if (p == pend) FREE_STACK_RETURN (REG_EESCAPE); - - /* Do not translate the character after the \, so that we can - distinguish, e.g., \B from \b, even if we normally would - translate, e.g., B to b. */ - PATFETCH_RAW (c); - - switch (c) - { - case '(': - if (syntax & RE_NO_BK_PARENS) - goto normal_backslash; - - handle_open: - bufp->re_nsub++; - regnum++; - - if (COMPILE_STACK_FULL) - { - RETALLOC (compile_stack.stack, compile_stack.size << 1, - compile_stack_elt_t); - if (compile_stack.stack == NULL) return REG_ESPACE; - - compile_stack.size <<= 1; - } - - /* These are the values to restore when we hit end of this - group. They are all relative offsets, so that if the - whole pattern moves because of realloc, they will still - be valid. */ - COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer; - COMPILE_STACK_TOP.fixup_alt_jump - = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0; - COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer; - COMPILE_STACK_TOP.regnum = regnum; - - /* We will eventually replace the 0 with the number of - groups inner to this one. But do not push a - start_memory for groups beyond the last one we can - represent in the compiled pattern. */ - if (regnum <= MAX_REGNUM) - { - COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2; - BUF_PUSH_3 (start_memory, regnum, 0); - } - - compile_stack.avail++; - - fixup_alt_jump = 0; - laststart = 0; - begalt = b; - /* If we've reached MAX_REGNUM groups, then this open - won't actually generate any code, so we'll have to - clear pending_exact explicitly. */ - pending_exact = 0; - break; - - - case ')': - if (syntax & RE_NO_BK_PARENS) goto normal_backslash; - - if (COMPILE_STACK_EMPTY) - if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD) - goto normal_backslash; - else - FREE_STACK_RETURN (REG_ERPAREN); - - handle_close: - if (fixup_alt_jump) - { /* Push a dummy failure point at the end of the - alternative for a possible future - `pop_failure_jump' to pop. See comments at - `push_dummy_failure' in `re_match_2'. */ - BUF_PUSH (push_dummy_failure); - - /* We allocated space for this jump when we assigned - to `fixup_alt_jump', in the `handle_alt' case below. */ - STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1); - } - - /* See similar code for backslashed left paren above. */ - if (COMPILE_STACK_EMPTY) - if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD) - goto normal_char; - else - FREE_STACK_RETURN (REG_ERPAREN); - - /* Since we just checked for an empty stack above, this - ``can't happen''. */ - assert (compile_stack.avail != 0); - { - /* We don't just want to restore into `regnum', because - later groups should continue to be numbered higher, - as in `(ab)c(de)' -- the second group is #2. */ - regnum_t this_group_regnum; - - compile_stack.avail--; - begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset; - fixup_alt_jump - = COMPILE_STACK_TOP.fixup_alt_jump - ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1 - : 0; - laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset; - this_group_regnum = COMPILE_STACK_TOP.regnum; - /* If we've reached MAX_REGNUM groups, then this open - won't actually generate any code, so we'll have to - clear pending_exact explicitly. */ - pending_exact = 0; - - /* We're at the end of the group, so now we know how many - groups were inside this one. */ - if (this_group_regnum <= MAX_REGNUM) - { - unsigned char *inner_group_loc - = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset; - - *inner_group_loc = regnum - this_group_regnum; - BUF_PUSH_3 (stop_memory, this_group_regnum, - regnum - this_group_regnum); - } - } - break; - - - case '|': /* `\|'. */ - if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR) - goto normal_backslash; - handle_alt: - if (syntax & RE_LIMITED_OPS) - goto normal_char; - - /* Insert before the previous alternative a jump which - jumps to this alternative if the former fails. */ - GET_BUFFER_SPACE (3); - INSERT_JUMP (on_failure_jump, begalt, b + 6); - pending_exact = 0; - b += 3; - - /* The alternative before this one has a jump after it - which gets executed if it gets matched. Adjust that - jump so it will jump to this alternative's analogous - jump (put in below, which in turn will jump to the next - (if any) alternative's such jump, etc.). The last such - jump jumps to the correct final destination. A picture: - _____ _____ - | | | | - | v | v - a | b | c - - If we are at `b', then fixup_alt_jump right now points to a - three-byte space after `a'. We'll put in the jump, set - fixup_alt_jump to right after `b', and leave behind three - bytes which we'll fill in when we get to after `c'. */ - - if (fixup_alt_jump) - STORE_JUMP (jump_past_alt, fixup_alt_jump, b); - - /* Mark and leave space for a jump after this alternative, - to be filled in later either by next alternative or - when know we're at the end of a series of alternatives. */ - fixup_alt_jump = b; - GET_BUFFER_SPACE (3); - b += 3; - - laststart = 0; - begalt = b; - break; - - - case '{': - /* If \{ is a literal. */ - if (!(syntax & RE_INTERVALS) - /* If we're at `\{' and it's not the open-interval - operator. */ - || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES)) - || (p - 2 == pattern && p == pend)) - goto normal_backslash; - - handle_interval: - { - /* If got here, then the syntax allows intervals. */ - - /* At least (most) this many matches must be made. */ - int lower_bound = -1, upper_bound = -1; - - beg_interval = p - 1; - - if (p == pend) - { - if (syntax & RE_NO_BK_BRACES) - goto unfetch_interval; - else - FREE_STACK_RETURN (REG_EBRACE); - } - - GET_UNSIGNED_NUMBER (lower_bound); - - if (c == ',') - { - GET_UNSIGNED_NUMBER (upper_bound); - if (upper_bound < 0) upper_bound = RE_DUP_MAX; - } - else - /* Interval such as `{1}' => match exactly once. */ - upper_bound = lower_bound; - - if (lower_bound < 0 || upper_bound > RE_DUP_MAX - || lower_bound > upper_bound) - { - if (syntax & RE_NO_BK_BRACES) - goto unfetch_interval; - else - FREE_STACK_RETURN (REG_BADBR); - } - - if (!(syntax & RE_NO_BK_BRACES)) - { - if (c != '\\') FREE_STACK_RETURN (REG_EBRACE); - - PATFETCH (c); - } - - if (c != '}') - { - if (syntax & RE_NO_BK_BRACES) - goto unfetch_interval; - else - FREE_STACK_RETURN (REG_BADBR); - } - - /* We just parsed a valid interval. */ - - /* If it's invalid to have no preceding re. */ - if (!laststart) - { - if (syntax & RE_CONTEXT_INVALID_OPS) - FREE_STACK_RETURN (REG_BADRPT); - else if (syntax & RE_CONTEXT_INDEP_OPS) - laststart = b; - else - goto unfetch_interval; - } - - /* If the upper bound is zero, don't want to succeed at - all; jump from `laststart' to `b + 3', which will be - the end of the buffer after we insert the jump. */ - if (upper_bound == 0) - { - GET_BUFFER_SPACE (3); - INSERT_JUMP (jump, laststart, b + 3); - b += 3; - } - - /* Otherwise, we have a nontrivial interval. When - we're all done, the pattern will look like: - set_number_at - set_number_at - succeed_n - - jump_n - (The upper bound and `jump_n' are omitted if - `upper_bound' is 1, though.) */ - else - { /* If the upper bound is > 1, we need to insert - more at the end of the loop. */ - unsigned nbytes = 10 + (upper_bound > 1) * 10; - - GET_BUFFER_SPACE (nbytes); - - /* Initialize lower bound of the `succeed_n', even - though it will be set during matching by its - attendant `set_number_at' (inserted next), - because `re_compile_fastmap' needs to know. - Jump to the `jump_n' we might insert below. */ - INSERT_JUMP2 (succeed_n, laststart, - b + 5 + (upper_bound > 1) * 5, - lower_bound); - b += 5; - - /* Code to initialize the lower bound. Insert - before the `succeed_n'. The `5' is the last two - bytes of this `set_number_at', plus 3 bytes of - the following `succeed_n'. */ - insert_op2 (set_number_at, laststart, 5, lower_bound, b); - b += 5; - - if (upper_bound > 1) - { /* More than one repetition is allowed, so - append a backward jump to the `succeed_n' - that starts this interval. - - When we've reached this during matching, - we'll have matched the interval once, so - jump back only `upper_bound - 1' times. */ - STORE_JUMP2 (jump_n, b, laststart + 5, - upper_bound - 1); - b += 5; - - /* The location we want to set is the second - parameter of the `jump_n'; that is `b-2' as - an absolute address. `laststart' will be - the `set_number_at' we're about to insert; - `laststart+3' the number to set, the source - for the relative address. But we are - inserting into the middle of the pattern -- - so everything is getting moved up by 5. - Conclusion: (b - 2) - (laststart + 3) + 5, - i.e., b - laststart. - - We insert this at the beginning of the loop - so that if we fail during matching, we'll - reinitialize the bounds. */ - insert_op2 (set_number_at, laststart, b - laststart, - upper_bound - 1, b); - b += 5; - } - } - pending_exact = 0; - beg_interval = NULL; - } - break; - - unfetch_interval: - /* If an invalid interval, match the characters as literals. */ - assert (beg_interval); - p = beg_interval; - beg_interval = NULL; - - /* normal_char and normal_backslash need `c'. */ - PATFETCH (c); - - if (!(syntax & RE_NO_BK_BRACES)) - { - if (p > pattern && p[-1] == '\\') - goto normal_backslash; - } - goto normal_char; - -#ifdef emacs - /* There is no way to specify the before_dot and after_dot - operators. rms says this is ok. --karl */ - case '=': - BUF_PUSH (at_dot); - break; - - case 's': - laststart = b; - PATFETCH (c); - BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]); - break; - - case 'S': - laststart = b; - PATFETCH (c); - BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]); - break; -#endif /* emacs */ - - - case 'w': - laststart = b; - BUF_PUSH (wordchar); - break; - - - case 'W': - laststart = b; - BUF_PUSH (notwordchar); - break; - - - case '<': - BUF_PUSH (wordbeg); - break; - - case '>': - BUF_PUSH (wordend); - break; - - case 'b': - BUF_PUSH (wordbound); - break; - - case 'B': - BUF_PUSH (notwordbound); - break; - - case '`': - BUF_PUSH (begbuf); - break; - - case '\'': - BUF_PUSH (endbuf); - break; - - case '1': case '2': case '3': case '4': case '5': - case '6': case '7': case '8': case '9': - if (syntax & RE_NO_BK_REFS) - goto normal_char; - - c1 = c - '0'; - - if (c1 > regnum) - FREE_STACK_RETURN (REG_ESUBREG); - - /* Can't back reference to a subexpression if inside of it. */ - if (group_in_compile_stack (compile_stack, c1)) - goto normal_char; - - laststart = b; - BUF_PUSH_2 (duplicate, c1); - break; - - - case '+': - case '?': - if (syntax & RE_BK_PLUS_QM) - goto handle_plus; - else - goto normal_backslash; - - default: - normal_backslash: - /* You might think it would be useful for \ to mean - not to translate; but if we don't translate it - it will never match anything. */ - c = TRANSLATE (c); - goto normal_char; - } - break; - - - default: - /* Expects the character in `c'. */ - normal_char: - /* If no exactn currently being built. */ - if (!pending_exact - - /* If last exactn not at current position. */ - || pending_exact + *pending_exact + 1 != b - - /* We have only one byte following the exactn for the count. */ - || *pending_exact == (1 << BYTEWIDTH) - 1 - - /* If followed by a repetition operator. */ - || *p == '*' || *p == '^' - || ((syntax & RE_BK_PLUS_QM) - ? *p == '\\' && (p[1] == '+' || p[1] == '?') - : (*p == '+' || *p == '?')) - || ((syntax & RE_INTERVALS) - && ((syntax & RE_NO_BK_BRACES) - ? *p == '{' - : (p[0] == '\\' && p[1] == '{')))) - { - /* Start building a new exactn. */ - - laststart = b; - - BUF_PUSH_2 (exactn, 0); - pending_exact = b - 1; - } - - BUF_PUSH (c); - (*pending_exact)++; - break; - } /* switch (c) */ - } /* while p != pend */ - - - /* Through the pattern now. */ - - if (fixup_alt_jump) - STORE_JUMP (jump_past_alt, fixup_alt_jump, b); - - if (!COMPILE_STACK_EMPTY) - FREE_STACK_RETURN (REG_EPAREN); - - free (compile_stack.stack); - - /* We have succeeded; set the length of the buffer. */ - bufp->used = b - bufp->buffer; - -#ifdef DEBUG - if (debug) - { - DEBUG_PRINT1 ("\nCompiled pattern: \n"); - print_compiled_pattern (bufp); - } -#endif /* DEBUG */ - -#ifndef MATCH_MAY_ALLOCATE - /* Initialize the failure stack to the largest possible stack. This - isn't necessary unless we're trying to avoid calling alloca in - the search and match routines. */ - { - int num_regs = bufp->re_nsub + 1; - - /* Since DOUBLE_FAIL_STACK refuses to double only if the current size - is strictly greater than re_max_failures, the largest possible stack - is 2 * re_max_failures failure points. */ - if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS)) - { - fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS); - -#ifdef emacs - if (! fail_stack.stack) - fail_stack.stack - = (fail_stack_elt_t *) xmalloc (fail_stack.size - * sizeof (fail_stack_elt_t)); - else - fail_stack.stack - = (fail_stack_elt_t *) xrealloc (fail_stack.stack, - (fail_stack.size - * sizeof (fail_stack_elt_t))); -#else /* not emacs */ - if (! fail_stack.stack) - fail_stack.stack - = (fail_stack_elt_t *) malloc (fail_stack.size - * sizeof (fail_stack_elt_t)); - else - fail_stack.stack - = (fail_stack_elt_t *) realloc (fail_stack.stack, - (fail_stack.size - * sizeof (fail_stack_elt_t))); -#endif /* not emacs */ - } - - /* Initialize some other variables the matcher uses. */ - RETALLOC_IF (regstart, num_regs, const char *); - RETALLOC_IF (regend, num_regs, const char *); - RETALLOC_IF (old_regstart, num_regs, const char *); - RETALLOC_IF (old_regend, num_regs, const char *); - RETALLOC_IF (best_regstart, num_regs, const char *); - RETALLOC_IF (best_regend, num_regs, const char *); - RETALLOC_IF (reg_info, num_regs, register_info_type); - RETALLOC_IF (reg_dummy, num_regs, const char *); - RETALLOC_IF (reg_info_dummy, num_regs, register_info_type); - } -#endif - - return REG_NOERROR; -} /* regex_compile */ - -/* Subroutines for `regex_compile'. */ - -/* Store OP at LOC followed by two-byte integer parameter ARG. */ - -static void -store_op1 (op, loc, arg) - re_opcode_t op; - unsigned char *loc; - int arg; -{ - *loc = (unsigned char) op; - STORE_NUMBER (loc + 1, arg); -} - - -/* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */ - -static void -store_op2 (op, loc, arg1, arg2) - re_opcode_t op; - unsigned char *loc; - int arg1, arg2; -{ - *loc = (unsigned char) op; - STORE_NUMBER (loc + 1, arg1); - STORE_NUMBER (loc + 3, arg2); -} - - -/* Copy the bytes from LOC to END to open up three bytes of space at LOC - for OP followed by two-byte integer parameter ARG. */ - -static void -insert_op1 (op, loc, arg, end) - re_opcode_t op; - unsigned char *loc; - int arg; - unsigned char *end; -{ - register unsigned char *pfrom = end; - register unsigned char *pto = end + 3; - - while (pfrom != loc) - *--pto = *--pfrom; - - store_op1 (op, loc, arg); -} - - -/* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */ - -static void -insert_op2 (op, loc, arg1, arg2, end) - re_opcode_t op; - unsigned char *loc; - int arg1, arg2; - unsigned char *end; -{ - register unsigned char *pfrom = end; - register unsigned char *pto = end + 5; - - while (pfrom != loc) - *--pto = *--pfrom; - - store_op2 (op, loc, arg1, arg2); -} - - -/* P points to just after a ^ in PATTERN. Return true if that ^ comes - after an alternative or a begin-subexpression. We assume there is at - least one character before the ^. */ - -static boolean -at_begline_loc_p (pattern, p, syntax) - const char *pattern, *p; - reg_syntax_t syntax; -{ - const char *prev = p - 2; - boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\'; - - return - /* After a subexpression? */ - (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash)) - /* After an alternative? */ - || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash)); -} - - -/* The dual of at_begline_loc_p. This one is for $. We assume there is - at least one character after the $, i.e., `P < PEND'. */ - -static boolean -at_endline_loc_p (p, pend, syntax) - const char *p, *pend; - int syntax; -{ - const char *next = p; - boolean next_backslash = *next == '\\'; - const char *next_next = p + 1 < pend ? p + 1 : NULL; - - return - /* Before a subexpression? */ - (syntax & RE_NO_BK_PARENS ? *next == ')' - : next_backslash && next_next && *next_next == ')') - /* Before an alternative? */ - || (syntax & RE_NO_BK_VBAR ? *next == '|' - : next_backslash && next_next && *next_next == '|'); -} - - -/* Returns true if REGNUM is in one of COMPILE_STACK's elements and - false if it's not. */ - -static boolean -group_in_compile_stack (compile_stack, regnum) - compile_stack_type compile_stack; - regnum_t regnum; -{ - int this_element; - - for (this_element = compile_stack.avail - 1; - this_element >= 0; - this_element--) - if (compile_stack.stack[this_element].regnum == regnum) - return true; - - return false; -} - - -/* Read the ending character of a range (in a bracket expression) from the - uncompiled pattern *P_PTR (which ends at PEND). We assume the - starting character is in `P[-2]'. (`P[-1]' is the character `-'.) - Then we set the translation of all bits between the starting and - ending characters (inclusive) in the compiled pattern B. - - Return an error code. - - We use these short variable names so we can use the same macros as - `regex_compile' itself. */ - -static reg_errcode_t -compile_range (p_ptr, pend, translate, syntax, b) - const char **p_ptr, *pend; - char *translate; - reg_syntax_t syntax; - unsigned char *b; -{ - unsigned this_char; - - const char *p = *p_ptr; - int range_start, range_end; - - if (p == pend) - return REG_ERANGE; - - /* Even though the pattern is a signed `char *', we need to fetch - with unsigned char *'s; if the high bit of the pattern character - is set, the range endpoints will be negative if we fetch using a - signed char *. - - We also want to fetch the endpoints without translating them; the - appropriate translation is done in the bit-setting loop below. */ - /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */ - range_start = ((const unsigned char *) p)[-2]; - range_end = ((const unsigned char *) p)[0]; - - /* Have to increment the pointer into the pattern string, so the - caller isn't still at the ending character. */ - (*p_ptr)++; - - /* If the start is after the end, the range is empty. */ - if (range_start > range_end) - return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR; - - /* Here we see why `this_char' has to be larger than an `unsigned - char' -- the range is inclusive, so if `range_end' == 0xff - (assuming 8-bit characters), we would otherwise go into an infinite - loop, since all characters <= 0xff. */ - for (this_char = range_start; this_char <= range_end; this_char++) - { - SET_LIST_BIT (TRANSLATE (this_char)); - } - - return REG_NOERROR; -} - -/* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in - BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible - characters can start a string that matches the pattern. This fastmap - is used by re_search to skip quickly over impossible starting points. - - The caller must supply the address of a (1 << BYTEWIDTH)-byte data - area as BUFP->fastmap. - - We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in - the pattern buffer. - - Returns 0 if we succeed, -2 if an internal error. */ - -int -re_compile_fastmap (bufp) - struct re_pattern_buffer *bufp; -{ - int j, k; -#ifdef MATCH_MAY_ALLOCATE - fail_stack_type fail_stack; -#endif -#ifndef REGEX_MALLOC - char *destination; -#endif - /* We don't push any register information onto the failure stack. */ - unsigned num_regs = 0; - - register char *fastmap = bufp->fastmap; - unsigned char *pattern = bufp->buffer; - unsigned long size = bufp->used; - unsigned char *p = pattern; - register unsigned char *pend = pattern + size; - - /* Assume that each path through the pattern can be null until - proven otherwise. We set this false at the bottom of switch - statement, to which we get only if a particular path doesn't - match the empty string. */ - boolean path_can_be_null = true; - - /* We aren't doing a `succeed_n' to begin with. */ - boolean succeed_n_p = false; - - assert (fastmap != NULL && p != NULL); - - INIT_FAIL_STACK (); - bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */ - bufp->fastmap_accurate = 1; /* It will be when we're done. */ - bufp->can_be_null = 0; - - while (p != pend || !FAIL_STACK_EMPTY ()) - { - if (p == pend) - { - bufp->can_be_null |= path_can_be_null; - - /* Reset for next path. */ - path_can_be_null = true; - - p = fail_stack.stack[--fail_stack.avail]; - } - - /* We should never be about to go beyond the end of the pattern. */ - assert (p < pend); - -#ifdef SWITCH_ENUM_BUG - switch ((int) ((re_opcode_t) *p++)) -#else - switch ((re_opcode_t) *p++) -#endif - { - - /* I guess the idea here is to simply not bother with a fastmap - if a backreference is used, since it's too hard to figure out - the fastmap for the corresponding group. Setting - `can_be_null' stops `re_search_2' from using the fastmap, so - that is all we do. */ - case duplicate: - bufp->can_be_null = 1; - return 0; - - - /* Following are the cases which match a character. These end - with `break'. */ - - case exactn: - fastmap[p[1]] = 1; - break; - - - case charset: - for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--) - if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) - fastmap[j] = 1; - break; - - - case charset_not: - /* Chars beyond end of map must be allowed. */ - for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++) - fastmap[j] = 1; - - for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--) - if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))) - fastmap[j] = 1; - break; - - - case wordchar: - for (j = 0; j < (1 << BYTEWIDTH); j++) - if (SYNTAX (j) == Sword) - fastmap[j] = 1; - break; - - - case notwordchar: - for (j = 0; j < (1 << BYTEWIDTH); j++) - if (SYNTAX (j) != Sword) - fastmap[j] = 1; - break; - - - case anychar: - { - int fastmap_newline = fastmap['\n']; - - /* `.' matches anything ... */ - for (j = 0; j < (1 << BYTEWIDTH); j++) - fastmap[j] = 1; - - /* ... except perhaps newline. */ - if (!(bufp->syntax & RE_DOT_NEWLINE)) - fastmap['\n'] = fastmap_newline; - - /* Return if we have already set `can_be_null'; if we have, - then the fastmap is irrelevant. Something's wrong here. */ - else if (bufp->can_be_null) - return 0; - - /* Otherwise, have to check alternative paths. */ - break; - } - -#ifdef emacs - case syntaxspec: - k = *p++; - for (j = 0; j < (1 << BYTEWIDTH); j++) - if (SYNTAX (j) == (enum syntaxcode) k) - fastmap[j] = 1; - break; - - - case notsyntaxspec: - k = *p++; - for (j = 0; j < (1 << BYTEWIDTH); j++) - if (SYNTAX (j) != (enum syntaxcode) k) - fastmap[j] = 1; - break; - - - /* All cases after this match the empty string. These end with - `continue'. */ - - - case before_dot: - case at_dot: - case after_dot: - continue; -#endif /* not emacs */ - - - case no_op: - case begline: - case endline: - case begbuf: - case endbuf: - case wordbound: - case notwordbound: - case wordbeg: - case wordend: - case push_dummy_failure: - continue; - - - case jump_n: - case pop_failure_jump: - case maybe_pop_jump: - case jump: - case jump_past_alt: - case dummy_failure_jump: - EXTRACT_NUMBER_AND_INCR (j, p); - p += j; - if (j > 0) - continue; - - /* Jump backward implies we just went through the body of a - loop and matched nothing. Opcode jumped to should be - `on_failure_jump' or `succeed_n'. Just treat it like an - ordinary jump. For a * loop, it has pushed its failure - point already; if so, discard that as redundant. */ - if ((re_opcode_t) *p != on_failure_jump - && (re_opcode_t) *p != succeed_n) - continue; - - p++; - EXTRACT_NUMBER_AND_INCR (j, p); - p += j; - - /* If what's on the stack is where we are now, pop it. */ - if (!FAIL_STACK_EMPTY () - && fail_stack.stack[fail_stack.avail - 1] == p) - fail_stack.avail--; - - continue; - - - case on_failure_jump: - case on_failure_keep_string_jump: - handle_on_failure_jump: - EXTRACT_NUMBER_AND_INCR (j, p); - - /* For some patterns, e.g., `(a?)?', `p+j' here points to the - end of the pattern. We don't want to push such a point, - since when we restore it above, entering the switch will - increment `p' past the end of the pattern. We don't need - to push such a point since we obviously won't find any more - fastmap entries beyond `pend'. Such a pattern can match - the null string, though. */ - if (p + j < pend) - { - if (!PUSH_PATTERN_OP (p + j, fail_stack)) - return -2; - } - else - bufp->can_be_null = 1; - - if (succeed_n_p) - { - EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */ - succeed_n_p = false; - } - - continue; - - - case succeed_n: - /* Get to the number of times to succeed. */ - p += 2; - - /* Increment p past the n for when k != 0. */ - EXTRACT_NUMBER_AND_INCR (k, p); - if (k == 0) - { - p -= 4; - succeed_n_p = true; /* Spaghetti code alert. */ - goto handle_on_failure_jump; - } - continue; - - - case set_number_at: - p += 4; - continue; - - - case start_memory: - case stop_memory: - p += 2; - continue; - - - default: - abort (); /* We have listed all the cases. */ - } /* switch *p++ */ - - /* Getting here means we have found the possible starting - characters for one path of the pattern -- and that the empty - string does not match. We need not follow this path further. - Instead, look at the next alternative (remembered on the - stack), or quit if no more. The test at the top of the loop - does these things. */ - path_can_be_null = false; - p = pend; - } /* while p */ - - /* Set `can_be_null' for the last path (also the first path, if the - pattern is empty). */ - bufp->can_be_null |= path_can_be_null; - return 0; -} /* re_compile_fastmap */ - -/* Set REGS to hold NUM_REGS registers, storing them in STARTS and - ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use - this memory for recording register information. STARTS and ENDS - must be allocated using the malloc library routine, and must each - be at least NUM_REGS * sizeof (regoff_t) bytes long. - - If NUM_REGS == 0, then subsequent matches should allocate their own - register data. - - Unless this function is called, the first search or match using - PATTERN_BUFFER will allocate its own register data, without - freeing the old data. */ - -void -re_set_registers (bufp, regs, num_regs, starts, ends) - struct re_pattern_buffer *bufp; - struct re_registers *regs; - unsigned num_regs; - regoff_t *starts, *ends; -{ - if (num_regs) - { - bufp->regs_allocated = REGS_REALLOCATE; - regs->num_regs = num_regs; - regs->start = starts; - regs->end = ends; - } - else - { - bufp->regs_allocated = REGS_UNALLOCATED; - regs->num_regs = 0; - regs->start = regs->end = (regoff_t *) 0; - } -} - -/* Searching routines. */ - -/* Like re_search_2, below, but only one string is specified, and - doesn't let you say where to stop matching. */ - -int -re_search (bufp, string, size, startpos, range, regs) - struct re_pattern_buffer *bufp; - const char *string; - int size, startpos, range; - struct re_registers *regs; -{ - return re_search_2 (bufp, NULL, 0, string, size, startpos, range, - regs, size); -} - - -/* Using the compiled pattern in BUFP->buffer, first tries to match the - virtual concatenation of STRING1 and STRING2, starting first at index - STARTPOS, then at STARTPOS + 1, and so on. - - STRING1 and STRING2 have length SIZE1 and SIZE2, respectively. - - RANGE is how far to scan while trying to match. RANGE = 0 means try - only at STARTPOS; in general, the last start tried is STARTPOS + - RANGE. - - In REGS, return the indices of the virtual concatenation of STRING1 - and STRING2 that matched the entire BUFP->buffer and its contained - subexpressions. - - Do not consider matching one past the index STOP in the virtual - concatenation of STRING1 and STRING2. - - We return either the position in the strings at which the match was - found, -1 if no match, or -2 if error (such as failure - stack overflow). */ - -int -re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop) - struct re_pattern_buffer *bufp; - const char *string1, *string2; - int size1, size2; - int startpos; - int range; - struct re_registers *regs; - int stop; -{ - int val; - register char *fastmap = bufp->fastmap; - register char *translate = bufp->translate; - int total_size = size1 + size2; - int endpos = startpos + range; - - /* Check for out-of-range STARTPOS. */ - if (startpos < 0 || startpos > total_size) - return -1; - - /* Fix up RANGE if it might eventually take us outside - the virtual concatenation of STRING1 and STRING2. */ - if (endpos < -1) - range = -1 - startpos; - else if (endpos > total_size) - range = total_size - startpos; - - /* If the search isn't to be a backwards one, don't waste time in a - search for a pattern that must be anchored. */ - if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0) - { - if (startpos > 0) - return -1; - else - range = 1; - } - - /* Update the fastmap now if not correct already. */ - if (fastmap && !bufp->fastmap_accurate) - if (re_compile_fastmap (bufp) == -2) - return -2; - - /* Loop through the string, looking for a place to start matching. */ - for (;;) - { - /* If a fastmap is supplied, skip quickly over characters that - cannot be the start of a match. If the pattern can match the - null string, however, we don't need to skip characters; we want - the first null string. */ - if (fastmap && startpos < total_size && !bufp->can_be_null) - { - if (range > 0) /* Searching forwards. */ - { - register const char *d; - register int lim = 0; - int irange = range; - - if (startpos < size1 && startpos + range >= size1) - lim = range - (size1 - startpos); - - d = (startpos >= size1 ? string2 - size1 : string1) + startpos; - - /* Written out as an if-else to avoid testing `translate' - inside the loop. */ - if (translate) - while (range > lim - && !fastmap[(unsigned char) - translate[(unsigned char) *d++]]) - range--; - else - while (range > lim && !fastmap[(unsigned char) *d++]) - range--; - - startpos += irange - range; - } - else /* Searching backwards. */ - { - register char c = (size1 == 0 || startpos >= size1 - ? string2[startpos - size1] - : string1[startpos]); - - if (!fastmap[(unsigned char) TRANSLATE (c)]) - goto advance; - } - } - - /* If can't match the null string, and that's all we have left, fail. */ - if (range >= 0 && startpos == total_size && fastmap - && !bufp->can_be_null) - return -1; - - val = re_match_2_internal (bufp, string1, size1, string2, size2, - startpos, regs, stop); -#ifndef REGEX_MALLOC -#ifdef C_ALLOCA - alloca (0); -#endif -#endif - - if (val >= 0) - return startpos; - - if (val == -2) - return -2; - - advance: - if (!range) - break; - else if (range > 0) - { - range--; - startpos++; - } - else - { - range++; - startpos--; - } - } - return -1; -} /* re_search_2 */ - -/* Declarations and macros for re_match_2. */ - -static int bcmp_translate (); -static boolean alt_match_null_string_p (), - common_op_match_null_string_p (), - group_match_null_string_p (); - -/* This converts PTR, a pointer into one of the search strings `string1' - and `string2' into an offset from the beginning of that string. */ -#define POINTER_TO_OFFSET(ptr) \ - (FIRST_STRING_P (ptr) \ - ? ((regoff_t) ((ptr) - string1)) \ - : ((regoff_t) ((ptr) - string2 + size1))) - -/* Macros for dealing with the split strings in re_match_2. */ - -#define MATCHING_IN_FIRST_STRING (dend == end_match_1) - -/* Call before fetching a character with *d. This switches over to - string2 if necessary. */ -#define PREFETCH() \ - while (d == dend) \ - { \ - /* End of string2 => fail. */ \ - if (dend == end_match_2) \ - goto fail; \ - /* End of string1 => advance to string2. */ \ - d = string2; \ - dend = end_match_2; \ - } - - -/* Test if at very beginning or at very end of the virtual concatenation - of `string1' and `string2'. If only one string, it's `string2'. */ -#define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2) -#define AT_STRINGS_END(d) ((d) == end2) - - -/* Test if D points to a character which is word-constituent. We have - two special cases to check for: if past the end of string1, look at - the first character in string2; and if before the beginning of - string2, look at the last character in string1. */ -#define WORDCHAR_P(d) \ - (SYNTAX ((d) == end1 ? *string2 \ - : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \ - == Sword) - -/* Test if the character before D and the one at D differ with respect - to being word-constituent. */ -#define AT_WORD_BOUNDARY(d) \ - (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \ - || WORDCHAR_P (d - 1) != WORDCHAR_P (d)) - - -/* Free everything we malloc. */ -#ifdef MATCH_MAY_ALLOCATE -#ifdef REGEX_MALLOC -#define FREE_VAR(var) if (var) free (var); var = NULL -#define FREE_VARIABLES() \ - do { \ - FREE_VAR (fail_stack.stack); \ - FREE_VAR (regstart); \ - FREE_VAR (regend); \ - FREE_VAR (old_regstart); \ - FREE_VAR (old_regend); \ - FREE_VAR (best_regstart); \ - FREE_VAR (best_regend); \ - FREE_VAR (reg_info); \ - FREE_VAR (reg_dummy); \ - FREE_VAR (reg_info_dummy); \ - } while (0) -#else /* not REGEX_MALLOC */ -/* This used to do alloca (0), but now we do that in the caller. */ -#define FREE_VARIABLES() /* Nothing */ -#endif /* not REGEX_MALLOC */ -#else -#define FREE_VARIABLES() /* Do nothing! */ -#endif /* not MATCH_MAY_ALLOCATE */ - -/* These values must meet several constraints. They must not be valid - register values; since we have a limit of 255 registers (because - we use only one byte in the pattern for the register number), we can - use numbers larger than 255. They must differ by 1, because of - NUM_FAILURE_ITEMS above. And the value for the lowest register must - be larger than the value for the highest register, so we do not try - to actually save any registers when none are active. */ -#define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH) -#define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1) - -/* Matching routines. */ - -#ifndef emacs /* Emacs never uses this. */ -/* re_match is like re_match_2 except it takes only a single string. */ - -int -re_match (bufp, string, size, pos, regs) - struct re_pattern_buffer *bufp; - const char *string; - int size, pos; - struct re_registers *regs; -{ - int result = re_match_2_internal (bufp, NULL, 0, string, size, - pos, regs, size); - alloca (0); - return result; -} -#endif /* not emacs */ - - -/* re_match_2 matches the compiled pattern in BUFP against the - the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1 - and SIZE2, respectively). We start matching at POS, and stop - matching at STOP. - - If REGS is non-null and the `no_sub' field of BUFP is nonzero, we - store offsets for the substring each group matched in REGS. See the - documentation for exactly how many groups we fill. - - We return -1 if no match, -2 if an internal error (such as the - failure stack overflowing). Otherwise, we return the length of the - matched substring. */ - -int -re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop) - struct re_pattern_buffer *bufp; - const char *string1, *string2; - int size1, size2; - int pos; - struct re_registers *regs; - int stop; -{ - int result = re_match_2_internal (bufp, string1, size1, string2, size2, - pos, regs, stop); - alloca (0); - return result; -} - -/* This is a separate function so that we can force an alloca cleanup - afterwards. */ -static int -re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop) - struct re_pattern_buffer *bufp; - const char *string1, *string2; - int size1, size2; - int pos; - struct re_registers *regs; - int stop; -{ - /* General temporaries. */ - int mcnt; - unsigned char *p1; - - /* Just past the end of the corresponding string. */ - const char *end1, *end2; - - /* Pointers into string1 and string2, just past the last characters in - each to consider matching. */ - const char *end_match_1, *end_match_2; - - /* Where we are in the data, and the end of the current string. */ - const char *d, *dend; - - /* Where we are in the pattern, and the end of the pattern. */ - unsigned char *p = bufp->buffer; - register unsigned char *pend = p + bufp->used; - - /* Mark the opcode just after a start_memory, so we can test for an - empty subpattern when we get to the stop_memory. */ - unsigned char *just_past_start_mem = 0; - - /* We use this to map every character in the string. */ - char *translate = bufp->translate; - - /* Failure point stack. Each place that can handle a failure further - down the line pushes a failure point on this stack. It consists of - restart, regend, and reg_info for all registers corresponding to - the subexpressions we're currently inside, plus the number of such - registers, and, finally, two char *'s. The first char * is where - to resume scanning the pattern; the second one is where to resume - scanning the strings. If the latter is zero, the failure point is - a ``dummy''; if a failure happens and the failure point is a dummy, - it gets discarded and the next next one is tried. */ -#ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */ - fail_stack_type fail_stack; -#endif -#ifdef DEBUG - static unsigned failure_id = 0; - unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0; -#endif - - /* We fill all the registers internally, independent of what we - return, for use in backreferences. The number here includes - an element for register zero. */ - unsigned num_regs = bufp->re_nsub + 1; - - /* The currently active registers. */ - unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG; - unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG; - - /* Information on the contents of registers. These are pointers into - the input strings; they record just what was matched (on this - attempt) by a subexpression part of the pattern, that is, the - regnum-th regstart pointer points to where in the pattern we began - matching and the regnum-th regend points to right after where we - stopped matching the regnum-th subexpression. (The zeroth register - keeps track of what the whole pattern matches.) */ -#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */ - const char **regstart, **regend; -#endif - - /* If a group that's operated upon by a repetition operator fails to - match anything, then the register for its start will need to be - restored because it will have been set to wherever in the string we - are when we last see its open-group operator. Similarly for a - register's end. */ -#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */ - const char **old_regstart, **old_regend; -#endif - - /* The is_active field of reg_info helps us keep track of which (possibly - nested) subexpressions we are currently in. The matched_something - field of reg_info[reg_num] helps us tell whether or not we have - matched any of the pattern so far this time through the reg_num-th - subexpression. These two fields get reset each time through any - loop their register is in. */ -#ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */ - register_info_type *reg_info; -#endif - - /* The following record the register info as found in the above - variables when we find a match better than any we've seen before. - This happens as we backtrack through the failure points, which in - turn happens only if we have not yet matched the entire string. */ - unsigned best_regs_set = false; -#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */ - const char **best_regstart, **best_regend; -#endif - - /* Logically, this is `best_regend[0]'. But we don't want to have to - allocate space for that if we're not allocating space for anything - else (see below). Also, we never need info about register 0 for - any of the other register vectors, and it seems rather a kludge to - treat `best_regend' differently than the rest. So we keep track of - the end of the best match so far in a separate variable. We - initialize this to NULL so that when we backtrack the first time - and need to test it, it's not garbage. */ - const char *match_end = NULL; - - /* Used when we pop values we don't care about. */ -#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */ - const char **reg_dummy; - register_info_type *reg_info_dummy; -#endif - -#ifdef DEBUG - /* Counts the total number of registers pushed. */ - unsigned num_regs_pushed = 0; -#endif - - DEBUG_PRINT1 ("\n\nEntering re_match_2.\n"); - - INIT_FAIL_STACK (); - -#ifdef MATCH_MAY_ALLOCATE - /* Do not bother to initialize all the register variables if there are - no groups in the pattern, as it takes a fair amount of time. If - there are groups, we include space for register 0 (the whole - pattern), even though we never use it, since it simplifies the - array indexing. We should fix this. */ - if (bufp->re_nsub) - { - regstart = REGEX_TALLOC (num_regs, const char *); - regend = REGEX_TALLOC (num_regs, const char *); - old_regstart = REGEX_TALLOC (num_regs, const char *); - old_regend = REGEX_TALLOC (num_regs, const char *); - best_regstart = REGEX_TALLOC (num_regs, const char *); - best_regend = REGEX_TALLOC (num_regs, const char *); - reg_info = REGEX_TALLOC (num_regs, register_info_type); - reg_dummy = REGEX_TALLOC (num_regs, const char *); - reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type); - - if (!(regstart && regend && old_regstart && old_regend && reg_info - && best_regstart && best_regend && reg_dummy && reg_info_dummy)) - { - FREE_VARIABLES (); - return -2; - } - } -#if defined (REGEX_MALLOC) - else - { - /* We must initialize all our variables to NULL, so that - `FREE_VARIABLES' doesn't try to free them. */ - regstart = regend = old_regstart = old_regend = best_regstart - = best_regend = reg_dummy = NULL; - reg_info = reg_info_dummy = (register_info_type *) NULL; - } -#endif /* REGEX_MALLOC */ -#endif /* MATCH_MAY_ALLOCATE */ - - /* The starting position is bogus. */ - if (pos < 0 || pos > size1 + size2) - { - FREE_VARIABLES (); - return -1; - } - - /* Initialize subexpression text positions to -1 to mark ones that no - start_memory/stop_memory has been seen for. Also initialize the - register information struct. */ - for (mcnt = 1; mcnt < num_regs; mcnt++) - { - regstart[mcnt] = regend[mcnt] - = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE; - - REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE; - IS_ACTIVE (reg_info[mcnt]) = 0; - MATCHED_SOMETHING (reg_info[mcnt]) = 0; - EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0; - } - - /* We move `string1' into `string2' if the latter's empty -- but not if - `string1' is null. */ - if (size2 == 0 && string1 != NULL) - { - string2 = string1; - size2 = size1; - string1 = 0; - size1 = 0; - } - end1 = string1 + size1; - end2 = string2 + size2; - - /* Compute where to stop matching, within the two strings. */ - if (stop <= size1) - { - end_match_1 = string1 + stop; - end_match_2 = string2; - } - else - { - end_match_1 = end1; - end_match_2 = string2 + stop - size1; - } - - /* `p' scans through the pattern as `d' scans through the data. - `dend' is the end of the input string that `d' points within. `d' - is advanced into the following input string whenever necessary, but - this happens before fetching; therefore, at the beginning of the - loop, `d' can be pointing at the end of a string, but it cannot - equal `string2'. */ - if (size1 > 0 && pos <= size1) - { - d = string1 + pos; - dend = end_match_1; - } - else - { - d = string2 + pos - size1; - dend = end_match_2; - } - - DEBUG_PRINT1 ("The compiled pattern is: "); - DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend); - DEBUG_PRINT1 ("The string to match is: `"); - DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2); - DEBUG_PRINT1 ("'\n"); - - /* This loops over pattern commands. It exits by returning from the - function if the match is complete, or it drops through if the match - fails at this starting point in the input data. */ - for (;;) - { - DEBUG_PRINT2 ("\n0x%x: ", p); - - if (p == pend) - { /* End of pattern means we might have succeeded. */ - DEBUG_PRINT1 ("end of pattern ... "); - - /* If we haven't matched the entire string, and we want the - longest match, try backtracking. */ - if (d != end_match_2) - { - /* 1 if this match ends in the same string (string1 or string2) - as the best previous match. */ - boolean same_str_p = (FIRST_STRING_P (match_end) - == MATCHING_IN_FIRST_STRING); - /* 1 if this match is the best seen so far. */ - boolean best_match_p; - - /* AIX compiler got confused when this was combined - with the previous declaration. */ - if (same_str_p) - best_match_p = d > match_end; - else - best_match_p = !MATCHING_IN_FIRST_STRING; - - DEBUG_PRINT1 ("backtracking.\n"); - - if (!FAIL_STACK_EMPTY ()) - { /* More failure points to try. */ - - /* If exceeds best match so far, save it. */ - if (!best_regs_set || best_match_p) - { - best_regs_set = true; - match_end = d; - - DEBUG_PRINT1 ("\nSAVING match as best so far.\n"); - - for (mcnt = 1; mcnt < num_regs; mcnt++) - { - best_regstart[mcnt] = regstart[mcnt]; - best_regend[mcnt] = regend[mcnt]; - } - } - goto fail; - } - - /* If no failure points, don't restore garbage. And if - last match is real best match, don't restore second - best one. */ - else if (best_regs_set && !best_match_p) - { - restore_best_regs: - /* Restore best match. It may happen that `dend == - end_match_1' while the restored d is in string2. - For example, the pattern `x.*y.*z' against the - strings `x-' and `y-z-', if the two strings are - not consecutive in memory. */ - DEBUG_PRINT1 ("Restoring best registers.\n"); - - d = match_end; - dend = ((d >= string1 && d <= end1) - ? end_match_1 : end_match_2); - - for (mcnt = 1; mcnt < num_regs; mcnt++) - { - regstart[mcnt] = best_regstart[mcnt]; - regend[mcnt] = best_regend[mcnt]; - } - } - } /* d != end_match_2 */ - - DEBUG_PRINT1 ("Accepting match.\n"); - - /* If caller wants register contents data back, do it. */ - if (regs && !bufp->no_sub) - { - /* Have the register data arrays been allocated? */ - if (bufp->regs_allocated == REGS_UNALLOCATED) - { /* No. So allocate them with malloc. We need one - extra element beyond `num_regs' for the `-1' marker - GNU code uses. */ - regs->num_regs = MAX (RE_NREGS, num_regs + 1); - regs->start = TALLOC (regs->num_regs, regoff_t); - regs->end = TALLOC (regs->num_regs, regoff_t); - if (regs->start == NULL || regs->end == NULL) - return -2; - bufp->regs_allocated = REGS_REALLOCATE; - } - else if (bufp->regs_allocated == REGS_REALLOCATE) - { /* Yes. If we need more elements than were already - allocated, reallocate them. If we need fewer, just - leave it alone. */ - if (regs->num_regs < num_regs + 1) - { - regs->num_regs = num_regs + 1; - RETALLOC (regs->start, regs->num_regs, regoff_t); - RETALLOC (regs->end, regs->num_regs, regoff_t); - if (regs->start == NULL || regs->end == NULL) - return -2; - } - } - else - { - /* These braces fend off a "empty body in an else-statement" - warning under GCC when assert expands to nothing. */ - assert (bufp->regs_allocated == REGS_FIXED); - } - - /* Convert the pointer data in `regstart' and `regend' to - indices. Register zero has to be set differently, - since we haven't kept track of any info for it. */ - if (regs->num_regs > 0) - { - regs->start[0] = pos; - regs->end[0] = (MATCHING_IN_FIRST_STRING - ? ((regoff_t) (d - string1)) - : ((regoff_t) (d - string2 + size1))); - } - - /* Go through the first `min (num_regs, regs->num_regs)' - registers, since that is all we initialized. */ - for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++) - { - if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt])) - regs->start[mcnt] = regs->end[mcnt] = -1; - else - { - regs->start[mcnt] - = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]); - regs->end[mcnt] - = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]); - } - } - - /* If the regs structure we return has more elements than - were in the pattern, set the extra elements to -1. If - we (re)allocated the registers, this is the case, - because we always allocate enough to have at least one - -1 at the end. */ - for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++) - regs->start[mcnt] = regs->end[mcnt] = -1; - } /* regs && !bufp->no_sub */ - - FREE_VARIABLES (); - DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n", - nfailure_points_pushed, nfailure_points_popped, - nfailure_points_pushed - nfailure_points_popped); - DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed); - - mcnt = d - pos - (MATCHING_IN_FIRST_STRING - ? string1 - : string2 - size1); - - DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt); - - return mcnt; - } - - /* Otherwise match next pattern command. */ -#ifdef SWITCH_ENUM_BUG - switch ((int) ((re_opcode_t) *p++)) -#else - switch ((re_opcode_t) *p++) -#endif - { - /* Ignore these. Used to ignore the n of succeed_n's which - currently have n == 0. */ - case no_op: - DEBUG_PRINT1 ("EXECUTING no_op.\n"); - break; - - - /* Match the next n pattern characters exactly. The following - byte in the pattern defines n, and the n bytes after that - are the characters to match. */ - case exactn: - mcnt = *p++; - DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt); - - /* This is written out as an if-else so we don't waste time - testing `translate' inside the loop. */ - if (translate) - { - do - { - PREFETCH (); - if (translate[(unsigned char) *d++] != (char) *p++) - goto fail; - } - while (--mcnt); - } - else - { - do - { - PREFETCH (); - if (*d++ != (char) *p++) goto fail; - } - while (--mcnt); - } - SET_REGS_MATCHED (); - break; - - - /* Match any character except possibly a newline or a null. */ - case anychar: - DEBUG_PRINT1 ("EXECUTING anychar.\n"); - - PREFETCH (); - - if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n') - || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000')) - goto fail; - - SET_REGS_MATCHED (); - DEBUG_PRINT2 (" Matched `%d'.\n", *d); - d++; - break; - - - case charset: - case charset_not: - { - register unsigned char c; - boolean not = (re_opcode_t) *(p - 1) == charset_not; - - DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : ""); - - PREFETCH (); - c = TRANSLATE (*d); /* The character to match. */ - - /* Cast to `unsigned' instead of `unsigned char' in case the - bit list is a full 32 bytes long. */ - if (c < (unsigned) (*p * BYTEWIDTH) - && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH))) - not = !not; - - p += 1 + *p; - - if (!not) goto fail; - - SET_REGS_MATCHED (); - d++; - break; - } - - - /* The beginning of a group is represented by start_memory. - The arguments are the register number in the next byte, and the - number of groups inner to this one in the next. The text - matched within the group is recorded (in the internal - registers data structure) under the register number. */ - case start_memory: - DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]); - - /* Find out if this group can match the empty string. */ - p1 = p; /* To send to group_match_null_string_p. */ - - if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE) - REG_MATCH_NULL_STRING_P (reg_info[*p]) - = group_match_null_string_p (&p1, pend, reg_info); - - /* Save the position in the string where we were the last time - we were at this open-group operator in case the group is - operated upon by a repetition operator, e.g., with `(a*)*b' - against `ab'; then we want to ignore where we are now in - the string in case this attempt to match fails. */ - old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p]) - ? REG_UNSET (regstart[*p]) ? d : regstart[*p] - : regstart[*p]; - DEBUG_PRINT2 (" old_regstart: %d\n", - POINTER_TO_OFFSET (old_regstart[*p])); - - regstart[*p] = d; - DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p])); - - IS_ACTIVE (reg_info[*p]) = 1; - MATCHED_SOMETHING (reg_info[*p]) = 0; - - /* This is the new highest active register. */ - highest_active_reg = *p; - - /* If nothing was active before, this is the new lowest active - register. */ - if (lowest_active_reg == NO_LOWEST_ACTIVE_REG) - lowest_active_reg = *p; - - /* Move past the register number and inner group count. */ - p += 2; - just_past_start_mem = p; - break; - - - /* The stop_memory opcode represents the end of a group. Its - arguments are the same as start_memory's: the register - number, and the number of inner groups. */ - case stop_memory: - DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]); - - /* We need to save the string position the last time we were at - this close-group operator in case the group is operated - upon by a repetition operator, e.g., with `((a*)*(b*)*)*' - against `aba'; then we want to ignore where we are now in - the string in case this attempt to match fails. */ - old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p]) - ? REG_UNSET (regend[*p]) ? d : regend[*p] - : regend[*p]; - DEBUG_PRINT2 (" old_regend: %d\n", - POINTER_TO_OFFSET (old_regend[*p])); - - regend[*p] = d; - DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p])); - - /* This register isn't active anymore. */ - IS_ACTIVE (reg_info[*p]) = 0; - - /* If this was the only register active, nothing is active - anymore. */ - if (lowest_active_reg == highest_active_reg) - { - lowest_active_reg = NO_LOWEST_ACTIVE_REG; - highest_active_reg = NO_HIGHEST_ACTIVE_REG; - } - else - { /* We must scan for the new highest active register, since - it isn't necessarily one less than now: consider - (a(b)c(d(e)f)g). When group 3 ends, after the f), the - new highest active register is 1. */ - unsigned char r = *p - 1; - while (r > 0 && !IS_ACTIVE (reg_info[r])) - r--; - - /* If we end up at register zero, that means that we saved - the registers as the result of an `on_failure_jump', not - a `start_memory', and we jumped to past the innermost - `stop_memory'. For example, in ((.)*) we save - registers 1 and 2 as a result of the *, but when we pop - back to the second ), we are at the stop_memory 1. - Thus, nothing is active. */ - if (r == 0) - { - lowest_active_reg = NO_LOWEST_ACTIVE_REG; - highest_active_reg = NO_HIGHEST_ACTIVE_REG; - } - else - highest_active_reg = r; - } - - /* If just failed to match something this time around with a - group that's operated on by a repetition operator, try to - force exit from the ``loop'', and restore the register - information for this group that we had before trying this - last match. */ - if ((!MATCHED_SOMETHING (reg_info[*p]) - || just_past_start_mem == p - 1) - && (p + 2) < pend) - { - boolean is_a_jump_n = false; - - p1 = p + 2; - mcnt = 0; - switch ((re_opcode_t) *p1++) - { - case jump_n: - is_a_jump_n = true; - case pop_failure_jump: - case maybe_pop_jump: - case jump: - case dummy_failure_jump: - EXTRACT_NUMBER_AND_INCR (mcnt, p1); - if (is_a_jump_n) - p1 += 2; - break; - - default: - /* do nothing */ ; - } - p1 += mcnt; - - /* If the next operation is a jump backwards in the pattern - to an on_failure_jump right before the start_memory - corresponding to this stop_memory, exit from the loop - by forcing a failure after pushing on the stack the - on_failure_jump's jump in the pattern, and d. */ - if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump - && (re_opcode_t) p1[3] == start_memory && p1[4] == *p) - { - /* If this group ever matched anything, then restore - what its registers were before trying this last - failed match, e.g., with `(a*)*b' against `ab' for - regstart[1], and, e.g., with `((a*)*(b*)*)*' - against `aba' for regend[3]. - - Also restore the registers for inner groups for, - e.g., `((a*)(b*))*' against `aba' (register 3 would - otherwise get trashed). */ - - if (EVER_MATCHED_SOMETHING (reg_info[*p])) - { - unsigned r; - - EVER_MATCHED_SOMETHING (reg_info[*p]) = 0; - - /* Restore this and inner groups' (if any) registers. */ - for (r = *p; r < *p + *(p + 1); r++) - { - regstart[r] = old_regstart[r]; - - /* xx why this test? */ - if ((int) old_regend[r] >= (int) regstart[r]) - regend[r] = old_regend[r]; - } - } - p1++; - EXTRACT_NUMBER_AND_INCR (mcnt, p1); - PUSH_FAILURE_POINT (p1 + mcnt, d, -2); - - goto fail; - } - } - - /* Move past the register number and the inner group count. */ - p += 2; - break; - - - /* \ has been turned into a `duplicate' command which is - followed by the numeric value of as the register number. */ - case duplicate: - { - register const char *d2, *dend2; - int regno = *p++; /* Get which register to match against. */ - DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno); - - /* Can't back reference a group which we've never matched. */ - if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno])) - goto fail; - - /* Where in input to try to start matching. */ - d2 = regstart[regno]; - - /* Where to stop matching; if both the place to start and - the place to stop matching are in the same string, then - set to the place to stop, otherwise, for now have to use - the end of the first string. */ - - dend2 = ((FIRST_STRING_P (regstart[regno]) - == FIRST_STRING_P (regend[regno])) - ? regend[regno] : end_match_1); - for (;;) - { - /* If necessary, advance to next segment in register - contents. */ - while (d2 == dend2) - { - if (dend2 == end_match_2) break; - if (dend2 == regend[regno]) break; - - /* End of string1 => advance to string2. */ - d2 = string2; - dend2 = regend[regno]; - } - /* At end of register contents => success */ - if (d2 == dend2) break; - - /* If necessary, advance to next segment in data. */ - PREFETCH (); - - /* How many characters left in this segment to match. */ - mcnt = dend - d; - - /* Want how many consecutive characters we can match in - one shot, so, if necessary, adjust the count. */ - if (mcnt > dend2 - d2) - mcnt = dend2 - d2; - - /* Compare that many; failure if mismatch, else move - past them. */ - if (translate - ? bcmp_translate (d, d2, mcnt, translate) - : bcmp (d, d2, mcnt)) - goto fail; - d += mcnt, d2 += mcnt; - } - } - break; - - - /* begline matches the empty string at the beginning of the string - (unless `not_bol' is set in `bufp'), and, if - `newline_anchor' is set, after newlines. */ - case begline: - DEBUG_PRINT1 ("EXECUTING begline.\n"); - - if (AT_STRINGS_BEG (d)) - { - if (!bufp->not_bol) break; - } - else if (d[-1] == '\n' && bufp->newline_anchor) - { - break; - } - /* In all other cases, we fail. */ - goto fail; - - - /* endline is the dual of begline. */ - case endline: - DEBUG_PRINT1 ("EXECUTING endline.\n"); - - if (AT_STRINGS_END (d)) - { - if (!bufp->not_eol) break; - } - - /* We have to ``prefetch'' the next character. */ - else if ((d == end1 ? *string2 : *d) == '\n' - && bufp->newline_anchor) - { - break; - } - goto fail; - - - /* Match at the very beginning of the data. */ - case begbuf: - DEBUG_PRINT1 ("EXECUTING begbuf.\n"); - if (AT_STRINGS_BEG (d)) - break; - goto fail; - - - /* Match at the very end of the data. */ - case endbuf: - DEBUG_PRINT1 ("EXECUTING endbuf.\n"); - if (AT_STRINGS_END (d)) - break; - goto fail; - - - /* on_failure_keep_string_jump is used to optimize `.*\n'. It - pushes NULL as the value for the string on the stack. Then - `pop_failure_point' will keep the current value for the - string, instead of restoring it. To see why, consider - matching `foo\nbar' against `.*\n'. The .* matches the foo; - then the . fails against the \n. But the next thing we want - to do is match the \n against the \n; if we restored the - string value, we would be back at the foo. - - Because this is used only in specific cases, we don't need to - check all the things that `on_failure_jump' does, to make - sure the right things get saved on the stack. Hence we don't - share its code. The only reason to push anything on the - stack at all is that otherwise we would have to change - `anychar's code to do something besides goto fail in this - case; that seems worse than this. */ - case on_failure_keep_string_jump: - DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump"); - - EXTRACT_NUMBER_AND_INCR (mcnt, p); - DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt); - - PUSH_FAILURE_POINT (p + mcnt, NULL, -2); - break; - - - /* Uses of on_failure_jump: - - Each alternative starts with an on_failure_jump that points - to the beginning of the next alternative. Each alternative - except the last ends with a jump that in effect jumps past - the rest of the alternatives. (They really jump to the - ending jump of the following alternative, because tensioning - these jumps is a hassle.) - - Repeats start with an on_failure_jump that points past both - the repetition text and either the following jump or - pop_failure_jump back to this on_failure_jump. */ - case on_failure_jump: - on_failure: - DEBUG_PRINT1 ("EXECUTING on_failure_jump"); - - EXTRACT_NUMBER_AND_INCR (mcnt, p); - DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt); - - /* If this on_failure_jump comes right before a group (i.e., - the original * applied to a group), save the information - for that group and all inner ones, so that if we fail back - to this point, the group's information will be correct. - For example, in \(a*\)*\1, we need the preceding group, - and in \(\(a*\)b*\)\2, we need the inner group. */ - - /* We can't use `p' to check ahead because we push - a failure point to `p + mcnt' after we do this. */ - p1 = p; - - /* We need to skip no_op's before we look for the - start_memory in case this on_failure_jump is happening as - the result of a completed succeed_n, as in \(a\)\{1,3\}b\1 - against aba. */ - while (p1 < pend && (re_opcode_t) *p1 == no_op) - p1++; - - if (p1 < pend && (re_opcode_t) *p1 == start_memory) - { - /* We have a new highest active register now. This will - get reset at the start_memory we are about to get to, - but we will have saved all the registers relevant to - this repetition op, as described above. */ - highest_active_reg = *(p1 + 1) + *(p1 + 2); - if (lowest_active_reg == NO_LOWEST_ACTIVE_REG) - lowest_active_reg = *(p1 + 1); - } - - DEBUG_PRINT1 (":\n"); - PUSH_FAILURE_POINT (p + mcnt, d, -2); - break; - - - /* A smart repeat ends with `maybe_pop_jump'. - We change it to either `pop_failure_jump' or `jump'. */ - case maybe_pop_jump: - EXTRACT_NUMBER_AND_INCR (mcnt, p); - DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt); - { - register unsigned char *p2 = p; - - /* Compare the beginning of the repeat with what in the - pattern follows its end. If we can establish that there - is nothing that they would both match, i.e., that we - would have to backtrack because of (as in, e.g., `a*a') - then we can change to pop_failure_jump, because we'll - never have to backtrack. - - This is not true in the case of alternatives: in - `(a|ab)*' we do need to backtrack to the `ab' alternative - (e.g., if the string was `ab'). But instead of trying to - detect that here, the alternative has put on a dummy - failure point which is what we will end up popping. */ - - /* Skip over open/close-group commands. - If what follows this loop is a ...+ construct, - look at what begins its body, since we will have to - match at least one of that. */ - while (1) - { - if (p2 + 2 < pend - && ((re_opcode_t) *p2 == stop_memory - || (re_opcode_t) *p2 == start_memory)) - p2 += 3; - else if (p2 + 6 < pend - && (re_opcode_t) *p2 == dummy_failure_jump) - p2 += 6; - else - break; - } - - p1 = p + mcnt; - /* p1[0] ... p1[2] are the `on_failure_jump' corresponding - to the `maybe_finalize_jump' of this case. Examine what - follows. */ - - /* If we're at the end of the pattern, we can change. */ - if (p2 == pend) - { - /* Consider what happens when matching ":\(.*\)" - against ":/". I don't really understand this code - yet. */ - p[-3] = (unsigned char) pop_failure_jump; - DEBUG_PRINT1 - (" End of pattern: change to `pop_failure_jump'.\n"); - } - - else if ((re_opcode_t) *p2 == exactn - || (bufp->newline_anchor && (re_opcode_t) *p2 == endline)) - { - register unsigned char c - = *p2 == (unsigned char) endline ? '\n' : p2[2]; - - if ((re_opcode_t) p1[3] == exactn && p1[5] != c) - { - p[-3] = (unsigned char) pop_failure_jump; - DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n", - c, p1[5]); - } - - else if ((re_opcode_t) p1[3] == charset - || (re_opcode_t) p1[3] == charset_not) - { - int not = (re_opcode_t) p1[3] == charset_not; - - if (c < (unsigned char) (p1[4] * BYTEWIDTH) - && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH))) - not = !not; - - /* `not' is equal to 1 if c would match, which means - that we can't change to pop_failure_jump. */ - if (!not) - { - p[-3] = (unsigned char) pop_failure_jump; - DEBUG_PRINT1 (" No match => pop_failure_jump.\n"); - } - } - } - else if ((re_opcode_t) *p2 == charset) - { -#ifdef DEBUG - register unsigned char c - = *p2 == (unsigned char) endline ? '\n' : p2[2]; -#endif - - if ((re_opcode_t) p1[3] == exactn - && ! ((int) p2[1] * BYTEWIDTH > (int) p1[4] - && (p2[1 + p1[4] / BYTEWIDTH] - & (1 << (p1[4] % BYTEWIDTH))))) - { - p[-3] = (unsigned char) pop_failure_jump; - DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n", - c, p1[5]); - } - - else if ((re_opcode_t) p1[3] == charset_not) - { - int idx; - /* We win if the charset_not inside the loop - lists every character listed in the charset after. */ - for (idx = 0; idx < (int) p2[1]; idx++) - if (! (p2[2 + idx] == 0 - || (idx < (int) p1[4] - && ((p2[2 + idx] & ~ p1[5 + idx]) == 0)))) - break; - - if (idx == p2[1]) - { - p[-3] = (unsigned char) pop_failure_jump; - DEBUG_PRINT1 (" No match => pop_failure_jump.\n"); - } - } - else if ((re_opcode_t) p1[3] == charset) - { - int idx; - /* We win if the charset inside the loop - has no overlap with the one after the loop. */ - for (idx = 0; - idx < (int) p2[1] && idx < (int) p1[4]; - idx++) - if ((p2[2 + idx] & p1[5 + idx]) != 0) - break; - - if (idx == p2[1] || idx == p1[4]) - { - p[-3] = (unsigned char) pop_failure_jump; - DEBUG_PRINT1 (" No match => pop_failure_jump.\n"); - } - } - } - } - p -= 2; /* Point at relative address again. */ - if ((re_opcode_t) p[-1] != pop_failure_jump) - { - p[-1] = (unsigned char) jump; - DEBUG_PRINT1 (" Match => jump.\n"); - goto unconditional_jump; - } - /* Note fall through. */ - - - /* The end of a simple repeat has a pop_failure_jump back to - its matching on_failure_jump, where the latter will push a - failure point. The pop_failure_jump takes off failure - points put on by this pop_failure_jump's matching - on_failure_jump; we got through the pattern to here from the - matching on_failure_jump, so didn't fail. */ - case pop_failure_jump: - { - /* We need to pass separate storage for the lowest and - highest registers, even though we don't care about the - actual values. Otherwise, we will restore only one - register from the stack, since lowest will == highest in - `pop_failure_point'. */ - unsigned dummy_low_reg, dummy_high_reg; - unsigned char *pdummy; - const char *sdummy; - - DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n"); - POP_FAILURE_POINT (sdummy, pdummy, - dummy_low_reg, dummy_high_reg, - reg_dummy, reg_dummy, reg_info_dummy); - } - /* Note fall through. */ - - - /* Unconditionally jump (without popping any failure points). */ - case jump: - unconditional_jump: - EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */ - DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt); - p += mcnt; /* Do the jump. */ - DEBUG_PRINT2 ("(to 0x%x).\n", p); - break; - - - /* We need this opcode so we can detect where alternatives end - in `group_match_null_string_p' et al. */ - case jump_past_alt: - DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n"); - goto unconditional_jump; - - - /* Normally, the on_failure_jump pushes a failure point, which - then gets popped at pop_failure_jump. We will end up at - pop_failure_jump, also, and with a pattern of, say, `a+', we - are skipping over the on_failure_jump, so we have to push - something meaningless for pop_failure_jump to pop. */ - case dummy_failure_jump: - DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n"); - /* It doesn't matter what we push for the string here. What - the code at `fail' tests is the value for the pattern. */ - PUSH_FAILURE_POINT (0, 0, -2); - goto unconditional_jump; - - - /* At the end of an alternative, we need to push a dummy failure - point in case we are followed by a `pop_failure_jump', because - we don't want the failure point for the alternative to be - popped. For example, matching `(a|ab)*' against `aab' - requires that we match the `ab' alternative. */ - case push_dummy_failure: - DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n"); - /* See comments just above at `dummy_failure_jump' about the - two zeroes. */ - PUSH_FAILURE_POINT (0, 0, -2); - break; - - /* Have to succeed matching what follows at least n times. - After that, handle like `on_failure_jump'. */ - case succeed_n: - EXTRACT_NUMBER (mcnt, p + 2); - DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt); - - assert (mcnt >= 0); - /* Originally, this is how many times we HAVE to succeed. */ - if (mcnt > 0) - { - mcnt--; - p += 2; - STORE_NUMBER_AND_INCR (p, mcnt); - DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt); - } - else if (mcnt == 0) - { - DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2); - p[2] = (unsigned char) no_op; - p[3] = (unsigned char) no_op; - goto on_failure; - } - break; - - case jump_n: - EXTRACT_NUMBER (mcnt, p + 2); - DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt); - - /* Originally, this is how many times we CAN jump. */ - if (mcnt) - { - mcnt--; - STORE_NUMBER (p + 2, mcnt); - goto unconditional_jump; - } - /* If don't have to jump any more, skip over the rest of command. */ - else - p += 4; - break; - - case set_number_at: - { - DEBUG_PRINT1 ("EXECUTING set_number_at.\n"); - - EXTRACT_NUMBER_AND_INCR (mcnt, p); - p1 = p + mcnt; - EXTRACT_NUMBER_AND_INCR (mcnt, p); - DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt); - STORE_NUMBER (p1, mcnt); - break; - } - - case wordbound: - DEBUG_PRINT1 ("EXECUTING wordbound.\n"); - if (AT_WORD_BOUNDARY (d)) - break; - goto fail; - - case notwordbound: - DEBUG_PRINT1 ("EXECUTING notwordbound.\n"); - if (AT_WORD_BOUNDARY (d)) - goto fail; - break; - - case wordbeg: - DEBUG_PRINT1 ("EXECUTING wordbeg.\n"); - if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1))) - break; - goto fail; - - case wordend: - DEBUG_PRINT1 ("EXECUTING wordend.\n"); - if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1) - && (!WORDCHAR_P (d) || AT_STRINGS_END (d))) - break; - goto fail; - -#ifdef emacs - case before_dot: - DEBUG_PRINT1 ("EXECUTING before_dot.\n"); - if (PTR_CHAR_POS ((unsigned char *) d) >= point) - goto fail; - break; - - case at_dot: - DEBUG_PRINT1 ("EXECUTING at_dot.\n"); - if (PTR_CHAR_POS ((unsigned char *) d) != point) - goto fail; - break; - - case after_dot: - DEBUG_PRINT1 ("EXECUTING after_dot.\n"); - if (PTR_CHAR_POS ((unsigned char *) d) <= point) - goto fail; - break; -#if 0 /* not emacs19 */ - case at_dot: - DEBUG_PRINT1 ("EXECUTING at_dot.\n"); - if (PTR_CHAR_POS ((unsigned char *) d) + 1 != point) - goto fail; - break; -#endif /* not emacs19 */ - - case syntaxspec: - DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt); - mcnt = *p++; - goto matchsyntax; - - case wordchar: - DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n"); - mcnt = (int) Sword; - matchsyntax: - PREFETCH (); - /* Can't use *d++ here; SYNTAX may be an unsafe macro. */ - d++; - if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt) - goto fail; - SET_REGS_MATCHED (); - break; - - case notsyntaxspec: - DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt); - mcnt = *p++; - goto matchnotsyntax; - - case notwordchar: - DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n"); - mcnt = (int) Sword; - matchnotsyntax: - PREFETCH (); - /* Can't use *d++ here; SYNTAX may be an unsafe macro. */ - d++; - if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt) - goto fail; - SET_REGS_MATCHED (); - break; - -#else /* not emacs */ - case wordchar: - DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n"); - PREFETCH (); - if (!WORDCHAR_P (d)) - goto fail; - SET_REGS_MATCHED (); - d++; - break; - - case notwordchar: - DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n"); - PREFETCH (); - if (WORDCHAR_P (d)) - goto fail; - SET_REGS_MATCHED (); - d++; - break; -#endif /* not emacs */ - - default: - abort (); - } - continue; /* Successfully executed one pattern command; keep going. */ - - - /* We goto here if a matching operation fails. */ - fail: - if (!FAIL_STACK_EMPTY ()) - { /* A restart point is known. Restore to that state. */ - DEBUG_PRINT1 ("\nFAIL:\n"); - POP_FAILURE_POINT (d, p, - lowest_active_reg, highest_active_reg, - regstart, regend, reg_info); - - /* If this failure point is a dummy, try the next one. */ - if (!p) - goto fail; - - /* If we failed to the end of the pattern, don't examine *p. */ - assert (p <= pend); - if (p < pend) - { - boolean is_a_jump_n = false; - - /* If failed to a backwards jump that's part of a repetition - loop, need to pop this failure point and use the next one. */ - switch ((re_opcode_t) *p) - { - case jump_n: - is_a_jump_n = true; - case maybe_pop_jump: - case pop_failure_jump: - case jump: - p1 = p + 1; - EXTRACT_NUMBER_AND_INCR (mcnt, p1); - p1 += mcnt; - - if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n) - || (!is_a_jump_n - && (re_opcode_t) *p1 == on_failure_jump)) - goto fail; - break; - default: - /* do nothing */ ; - } - } - - if (d >= string1 && d <= end1) - dend = end_match_1; - } - else - break; /* Matching at this starting point really fails. */ - } /* for (;;) */ - - if (best_regs_set) - goto restore_best_regs; - - FREE_VARIABLES (); - - return -1; /* Failure to match. */ -} /* re_match_2 */ - -/* Subroutine definitions for re_match_2. */ - - -/* We are passed P pointing to a register number after a start_memory. - - Return true if the pattern up to the corresponding stop_memory can - match the empty string, and false otherwise. - - If we find the matching stop_memory, sets P to point to one past its number. - Otherwise, sets P to an undefined byte less than or equal to END. - - We don't handle duplicates properly (yet). */ - -static boolean -group_match_null_string_p (p, end, reg_info) - unsigned char **p, *end; - register_info_type *reg_info; -{ - int mcnt; - /* Point to after the args to the start_memory. */ - unsigned char *p1 = *p + 2; - - while (p1 < end) - { - /* Skip over opcodes that can match nothing, and return true or - false, as appropriate, when we get to one that can't, or to the - matching stop_memory. */ - - switch ((re_opcode_t) *p1) - { - /* Could be either a loop or a series of alternatives. */ - case on_failure_jump: - p1++; - EXTRACT_NUMBER_AND_INCR (mcnt, p1); - - /* If the next operation is not a jump backwards in the - pattern. */ - - if (mcnt >= 0) - { - /* Go through the on_failure_jumps of the alternatives, - seeing if any of the alternatives cannot match nothing. - The last alternative starts with only a jump, - whereas the rest start with on_failure_jump and end - with a jump, e.g., here is the pattern for `a|b|c': - - /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6 - /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3 - /exactn/1/c - - So, we have to first go through the first (n-1) - alternatives and then deal with the last one separately. */ - - - /* Deal with the first (n-1) alternatives, which start - with an on_failure_jump (see above) that jumps to right - past a jump_past_alt. */ - - while ((re_opcode_t) p1[mcnt-3] == jump_past_alt) - { - /* `mcnt' holds how many bytes long the alternative - is, including the ending `jump_past_alt' and - its number. */ - - if (!alt_match_null_string_p (p1, p1 + mcnt - 3, - reg_info)) - return false; - - /* Move to right after this alternative, including the - jump_past_alt. */ - p1 += mcnt; - - /* Break if it's the beginning of an n-th alternative - that doesn't begin with an on_failure_jump. */ - if ((re_opcode_t) *p1 != on_failure_jump) - break; - - /* Still have to check that it's not an n-th - alternative that starts with an on_failure_jump. */ - p1++; - EXTRACT_NUMBER_AND_INCR (mcnt, p1); - if ((re_opcode_t) p1[mcnt-3] != jump_past_alt) - { - /* Get to the beginning of the n-th alternative. */ - p1 -= 3; - break; - } - } - - /* Deal with the last alternative: go back and get number - of the `jump_past_alt' just before it. `mcnt' contains - the length of the alternative. */ - EXTRACT_NUMBER (mcnt, p1 - 2); - - if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info)) - return false; - - p1 += mcnt; /* Get past the n-th alternative. */ - } /* if mcnt > 0 */ - break; - - - case stop_memory: - assert (p1[1] == **p); - *p = p1 + 2; - return true; - - - default: - if (!common_op_match_null_string_p (&p1, end, reg_info)) - return false; - } - } /* while p1 < end */ - - return false; -} /* group_match_null_string_p */ - - -/* Similar to group_match_null_string_p, but doesn't deal with alternatives: - It expects P to be the first byte of a single alternative and END one - byte past the last. The alternative can contain groups. */ - -static boolean -alt_match_null_string_p (p, end, reg_info) - unsigned char *p, *end; - register_info_type *reg_info; -{ - int mcnt; - unsigned char *p1 = p; - - while (p1 < end) - { - /* Skip over opcodes that can match nothing, and break when we get - to one that can't. */ - - switch ((re_opcode_t) *p1) - { - /* It's a loop. */ - case on_failure_jump: - p1++; - EXTRACT_NUMBER_AND_INCR (mcnt, p1); - p1 += mcnt; - break; - - default: - if (!common_op_match_null_string_p (&p1, end, reg_info)) - return false; - } - } /* while p1 < end */ - - return true; -} /* alt_match_null_string_p */ - - -/* Deals with the ops common to group_match_null_string_p and - alt_match_null_string_p. - - Sets P to one after the op and its arguments, if any. */ - -static boolean -common_op_match_null_string_p (p, end, reg_info) - unsigned char **p, *end; - register_info_type *reg_info; -{ - int mcnt; - boolean ret; - int reg_no; - unsigned char *p1 = *p; - - switch ((re_opcode_t) *p1++) - { - case no_op: - case begline: - case endline: - case begbuf: - case endbuf: - case wordbeg: - case wordend: - case wordbound: - case notwordbound: -#ifdef emacs - case before_dot: - case at_dot: - case after_dot: -#endif - break; - - case start_memory: - reg_no = *p1; - assert (reg_no > 0 && reg_no <= MAX_REGNUM); - ret = group_match_null_string_p (&p1, end, reg_info); - - /* Have to set this here in case we're checking a group which - contains a group and a back reference to it. */ - - if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE) - REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret; - - if (!ret) - return false; - break; - - /* If this is an optimized succeed_n for zero times, make the jump. */ - case jump: - EXTRACT_NUMBER_AND_INCR (mcnt, p1); - if (mcnt >= 0) - p1 += mcnt; - else - return false; - break; - - case succeed_n: - /* Get to the number of times to succeed. */ - p1 += 2; - EXTRACT_NUMBER_AND_INCR (mcnt, p1); - - if (mcnt == 0) - { - p1 -= 4; - EXTRACT_NUMBER_AND_INCR (mcnt, p1); - p1 += mcnt; - } - else - return false; - break; - - case duplicate: - if (!REG_MATCH_NULL_STRING_P (reg_info[*p1])) - return false; - break; - - case set_number_at: - p1 += 4; - - default: - /* All other opcodes mean we cannot match the empty string. */ - return false; - } - - *p = p1; - return true; -} /* common_op_match_null_string_p */ - - -/* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN - bytes; nonzero otherwise. */ - -static int -bcmp_translate (s1, s2, len, translate) - unsigned char *s1, *s2; - register int len; - char *translate; -{ - register unsigned char *p1 = s1, *p2 = s2; - while (len) - { - if (translate[*p1++] != translate[*p2++]) return 1; - len--; - } - return 0; -} - -/* Entry points for GNU code. */ - -/* re_compile_pattern is the GNU regular expression compiler: it - compiles PATTERN (of length SIZE) and puts the result in BUFP. - Returns 0 if the pattern was valid, otherwise an error string. - - Assumes the `allocated' (and perhaps `buffer') and `translate' fields - are set in BUFP on entry. - - We call regex_compile to do the actual compilation. */ - -const char * -re_compile_pattern (pattern, length, bufp) - const char *pattern; - int length; - struct re_pattern_buffer *bufp; -{ - reg_errcode_t ret; - - /* GNU code is written to assume at least RE_NREGS registers will be set - (and at least one extra will be -1). */ - bufp->regs_allocated = REGS_UNALLOCATED; - - /* And GNU code determines whether or not to get register information - by passing null for the REGS argument to re_match, etc., not by - setting no_sub. */ - bufp->no_sub = 0; - - /* Match anchors at newline. */ - bufp->newline_anchor = 1; - - ret = regex_compile (pattern, length, re_syntax_options, bufp); - - return re_error_msg[(int) ret]; -} - -/* Entry points compatible with 4.2 BSD regex library. We don't define - them unless specifically requested. */ - -#ifdef _REGEX_RE_COMP - -/* BSD has one and only one pattern buffer. */ -static struct re_pattern_buffer re_comp_buf; - -char * -re_comp (s) - const char *s; -{ - reg_errcode_t ret; - - if (!s) - { - if (!re_comp_buf.buffer) - return "No previous regular expression"; - return 0; - } - - if (!re_comp_buf.buffer) - { - re_comp_buf.buffer = (unsigned char *) malloc (200); - if (re_comp_buf.buffer == NULL) - return "Memory exhausted"; - re_comp_buf.allocated = 200; - - re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH); - if (re_comp_buf.fastmap == NULL) - return "Memory exhausted"; - } - - /* Since `re_exec' always passes NULL for the `regs' argument, we - don't need to initialize the pattern buffer fields which affect it. */ - - /* Match anchors at newlines. */ - re_comp_buf.newline_anchor = 1; - - ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf); - - /* Yes, we're discarding `const' here. */ - return (char *) re_error_msg[(int) ret]; -} - - -int -re_exec (s) - const char *s; -{ - const int len = strlen (s); - return - 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0); -} -#endif /* _REGEX_RE_COMP */ - -/* POSIX.2 functions. Don't define these for Emacs. */ - -#ifndef emacs - -/* regcomp takes a regular expression as a string and compiles it. - - PREG is a regex_t *. We do not expect any fields to be initialized, - since POSIX says we shouldn't. Thus, we set - - `buffer' to the compiled pattern; - `used' to the length of the compiled pattern; - `syntax' to RE_SYNTAX_POSIX_EXTENDED if the - REG_EXTENDED bit in CFLAGS is set; otherwise, to - RE_SYNTAX_POSIX_BASIC; - `newline_anchor' to REG_NEWLINE being set in CFLAGS; - `fastmap' and `fastmap_accurate' to zero; - `re_nsub' to the number of subexpressions in PATTERN. - - PATTERN is the address of the pattern string. - - CFLAGS is a series of bits which affect compilation. - - If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we - use POSIX basic syntax. - - If REG_NEWLINE is set, then . and [^...] don't match newline. - Also, regexec will try a match beginning after every newline. - - If REG_ICASE is set, then we considers upper- and lowercase - versions of letters to be equivalent when matching. - - If REG_NOSUB is set, then when PREG is passed to regexec, that - routine will report only success or failure, and nothing about the - registers. - - It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for - the return codes and their meanings.) */ - -int -regcomp (preg, pattern, cflags) - regex_t *preg; - const char *pattern; - int cflags; -{ - reg_errcode_t ret; - unsigned syntax - = (cflags & REG_EXTENDED) ? - RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC; - - /* regex_compile will allocate the space for the compiled pattern. */ - preg->buffer = 0; - preg->allocated = 0; - preg->used = 0; - - /* Don't bother to use a fastmap when searching. This simplifies the - REG_NEWLINE case: if we used a fastmap, we'd have to put all the - characters after newlines into the fastmap. This way, we just try - every character. */ - preg->fastmap = 0; - - if (cflags & REG_ICASE) - { - unsigned i; - - preg->translate = (char *) malloc (CHAR_SET_SIZE); - if (preg->translate == NULL) - return (int) REG_ESPACE; - - /* Map uppercase characters to corresponding lowercase ones. */ - for (i = 0; i < CHAR_SET_SIZE; i++) - preg->translate[i] = ISUPPER (i) ? tolower (i) : i; - } - else - preg->translate = NULL; - - /* If REG_NEWLINE is set, newlines are treated differently. */ - if (cflags & REG_NEWLINE) - { /* REG_NEWLINE implies neither . nor [^...] match newline. */ - syntax &= ~RE_DOT_NEWLINE; - syntax |= RE_HAT_LISTS_NOT_NEWLINE; - /* It also changes the matching behavior. */ - preg->newline_anchor = 1; - } - else - preg->newline_anchor = 0; - - preg->no_sub = !!(cflags & REG_NOSUB); - - /* POSIX says a null character in the pattern terminates it, so we - can use strlen here in compiling the pattern. */ - ret = regex_compile (pattern, strlen (pattern), syntax, preg); - - /* POSIX doesn't distinguish between an unmatched open-group and an - unmatched close-group: both are REG_EPAREN. */ - if (ret == REG_ERPAREN) ret = REG_EPAREN; - - return (int) ret; -} - - -/* regexec searches for a given pattern, specified by PREG, in the - string STRING. - - If NMATCH is zero or REG_NOSUB was set in the cflags argument to - `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at - least NMATCH elements, and we set them to the offsets of the - corresponding matched substrings. - - EFLAGS specifies `execution flags' which affect matching: if - REG_NOTBOL is set, then ^ does not match at the beginning of the - string; if REG_NOTEOL is set, then $ does not match at the end. - - We return 0 if we find a match and REG_NOMATCH if not. */ - -int -regexec (preg, string, nmatch, pmatch, eflags) - const regex_t *preg; - const char *string; - size_t nmatch; - regmatch_t pmatch[]; - int eflags; -{ - int ret; - struct re_registers regs; - regex_t private_preg; - int len = strlen (string); - boolean want_reg_info = !preg->no_sub && nmatch > 0; - - private_preg = *preg; - - private_preg.not_bol = !!(eflags & REG_NOTBOL); - private_preg.not_eol = !!(eflags & REG_NOTEOL); - - /* The user has told us exactly how many registers to return - information about, via `nmatch'. We have to pass that on to the - matching routines. */ - private_preg.regs_allocated = REGS_FIXED; - - if (want_reg_info) - { - regs.num_regs = nmatch; - regs.start = TALLOC (nmatch, regoff_t); - regs.end = TALLOC (nmatch, regoff_t); - if (regs.start == NULL || regs.end == NULL) - return (int) REG_NOMATCH; - } - - /* Perform the searching operation. */ - ret = re_search (&private_preg, string, len, - /* start: */ 0, /* range: */ len, - want_reg_info ? ®s : (struct re_registers *) 0); - - /* Copy the register information to the POSIX structure. */ - if (want_reg_info) - { - if (ret >= 0) - { - unsigned r; - - for (r = 0; r < nmatch; r++) - { - pmatch[r].rm_so = regs.start[r]; - pmatch[r].rm_eo = regs.end[r]; - } - } - - /* If we needed the temporary register info, free the space now. */ - free (regs.start); - free (regs.end); - } - - /* We want zero return to mean success, unlike `re_search'. */ - return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH; -} - - -/* Returns a message corresponding to an error code, ERRCODE, returned - from either regcomp or regexec. We don't use PREG here. */ - -size_t -regerror (errcode, preg, errbuf, errbuf_size) - int errcode; - const regex_t *preg; - char *errbuf; - size_t errbuf_size; -{ - const char *msg; - size_t msg_size; - - if (errcode < 0 - || errcode >= (sizeof (re_error_msg) / sizeof (re_error_msg[0]))) - /* Only error codes returned by the rest of the code should be passed - to this routine. If we are given anything else, or if other regex - code generates an invalid error code, then the program has a bug. - Dump core so we can fix it. */ - abort (); - - msg = re_error_msg[errcode]; - - /* POSIX doesn't require that we do anything in this case, but why - not be nice. */ - if (! msg) - msg = "Success"; - - msg_size = strlen (msg) + 1; /* Includes the null. */ - - if (errbuf_size != 0) - { - if (msg_size > errbuf_size) - { - strncpy (errbuf, msg, errbuf_size - 1); - errbuf[errbuf_size - 1] = 0; - } - else - strcpy (errbuf, msg); - } - - return msg_size; -} - - -/* Free dynamically allocated space used by PREG. */ - -void -regfree (preg) - regex_t *preg; -{ - if (preg->buffer != NULL) - free (preg->buffer); - preg->buffer = NULL; - - preg->allocated = 0; - preg->used = 0; - - if (preg->fastmap != NULL) - free (preg->fastmap); - preg->fastmap = NULL; - preg->fastmap_accurate = 0; - - if (preg->translate != NULL) - free (preg->translate); - preg->translate = NULL; -} - -#endif /* not emacs */ - -/* -Local variables: -make-backup-files: t -version-control: t -trim-versions-without-asking: nil -End: -*/ diff --git a/src/bin/findutils/lib/regex.h b/src/bin/findutils/lib/regex.h deleted file mode 100644 index 55927f627c..0000000000 --- a/src/bin/findutils/lib/regex.h +++ /dev/null @@ -1,487 +0,0 @@ -/* Definitions for data structures and routines for the regular - expression library, version 0.12. - - Copyright (C) 1985, 89, 90, 91, 92, 1993 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -#ifndef __REGEXP_LIBRARY_H__ -#define __REGEXP_LIBRARY_H__ - -/* POSIX says that must be included (by the caller) before - . */ - -#ifdef VMS -/* VMS doesn't have `size_t' in , even though POSIX says it - should be there. */ -#include -#endif - - -/* The following bits are used to determine the regexp syntax we - recognize. The set/not-set meanings are chosen so that Emacs syntax - remains the value 0. The bits are given in alphabetical order, and - the definitions shifted by one from the previous bit; thus, when we - add or remove a bit, only one other definition need change. */ -typedef unsigned reg_syntax_t; - -/* If this bit is not set, then \ inside a bracket expression is literal. - If set, then such a \ quotes the following character. */ -#define RE_BACKSLASH_ESCAPE_IN_LISTS (1) - -/* If this bit is not set, then + and ? are operators, and \+ and \? are - literals. - If set, then \+ and \? are operators and + and ? are literals. */ -#define RE_BK_PLUS_QM (RE_BACKSLASH_ESCAPE_IN_LISTS << 1) - -/* If this bit is set, then character classes are supported. They are: - [:alpha:], [:upper:], [:lower:], [:digit:], [:alnum:], [:xdigit:], - [:space:], [:print:], [:punct:], [:graph:], and [:cntrl:]. - If not set, then character classes are not supported. */ -#define RE_CHAR_CLASSES (RE_BK_PLUS_QM << 1) - -/* If this bit is set, then ^ and $ are always anchors (outside bracket - expressions, of course). - If this bit is not set, then it depends: - ^ is an anchor if it is at the beginning of a regular - expression or after an open-group or an alternation operator; - $ is an anchor if it is at the end of a regular expression, or - before a close-group or an alternation operator. - - This bit could be (re)combined with RE_CONTEXT_INDEP_OPS, because - POSIX draft 11.2 says that * etc. in leading positions is undefined. - We already implemented a previous draft which made those constructs - invalid, though, so we haven't changed the code back. */ -#define RE_CONTEXT_INDEP_ANCHORS (RE_CHAR_CLASSES << 1) - -/* If this bit is set, then special characters are always special - regardless of where they are in the pattern. - If this bit is not set, then special characters are special only in - some contexts; otherwise they are ordinary. Specifically, - * + ? and intervals are only special when not after the beginning, - open-group, or alternation operator. */ -#define RE_CONTEXT_INDEP_OPS (RE_CONTEXT_INDEP_ANCHORS << 1) - -/* If this bit is set, then *, +, ?, and { cannot be first in an re or - immediately after an alternation or begin-group operator. */ -#define RE_CONTEXT_INVALID_OPS (RE_CONTEXT_INDEP_OPS << 1) - -/* If this bit is set, then . matches newline. - If not set, then it doesn't. */ -#define RE_DOT_NEWLINE (RE_CONTEXT_INVALID_OPS << 1) - -/* If this bit is set, then . doesn't match NUL. - If not set, then it does. */ -#define RE_DOT_NOT_NULL (RE_DOT_NEWLINE << 1) - -/* If this bit is set, nonmatching lists [^...] do not match newline. - If not set, they do. */ -#define RE_HAT_LISTS_NOT_NEWLINE (RE_DOT_NOT_NULL << 1) - -/* If this bit is set, either \{...\} or {...} defines an - interval, depending on RE_NO_BK_BRACES. - If not set, \{, \}, {, and } are literals. */ -#define RE_INTERVALS (RE_HAT_LISTS_NOT_NEWLINE << 1) - -/* If this bit is set, +, ? and | aren't recognized as operators. - If not set, they are. */ -#define RE_LIMITED_OPS (RE_INTERVALS << 1) - -/* If this bit is set, newline is an alternation operator. - If not set, newline is literal. */ -#define RE_NEWLINE_ALT (RE_LIMITED_OPS << 1) - -/* If this bit is set, then `{...}' defines an interval, and \{ and \} - are literals. - If not set, then `\{...\}' defines an interval. */ -#define RE_NO_BK_BRACES (RE_NEWLINE_ALT << 1) - -/* If this bit is set, (...) defines a group, and \( and \) are literals. - If not set, \(...\) defines a group, and ( and ) are literals. */ -#define RE_NO_BK_PARENS (RE_NO_BK_BRACES << 1) - -/* If this bit is set, then \ matches . - If not set, then \ is a back-reference. */ -#define RE_NO_BK_REFS (RE_NO_BK_PARENS << 1) - -/* If this bit is set, then | is an alternation operator, and \| is literal. - If not set, then \| is an alternation operator, and | is literal. */ -#define RE_NO_BK_VBAR (RE_NO_BK_REFS << 1) - -/* If this bit is set, then an ending range point collating higher - than the starting range point, as in [z-a], is invalid. - If not set, then when ending range point collates higher than the - starting range point, the range is ignored. */ -#define RE_NO_EMPTY_RANGES (RE_NO_BK_VBAR << 1) - -/* If this bit is set, then an unmatched ) is ordinary. - If not set, then an unmatched ) is invalid. */ -#define RE_UNMATCHED_RIGHT_PAREN_ORD (RE_NO_EMPTY_RANGES << 1) - -/* This global variable defines the particular regexp syntax to use (for - some interfaces). When a regexp is compiled, the syntax used is - stored in the pattern buffer, so changing this does not affect - already-compiled regexps. */ -extern reg_syntax_t re_syntax_options; - -/* Define combinations of the above bits for the standard possibilities. - (The [[[ comments delimit what gets put into the Texinfo file, so - don't delete them!) */ -/* [[[begin syntaxes]]] */ -#define RE_SYNTAX_EMACS 0 - -#define RE_SYNTAX_AWK \ - (RE_BACKSLASH_ESCAPE_IN_LISTS | RE_DOT_NOT_NULL \ - | RE_NO_BK_PARENS | RE_NO_BK_REFS \ - | RE_NO_BK_VBAR | RE_NO_EMPTY_RANGES \ - | RE_UNMATCHED_RIGHT_PAREN_ORD) - -#define RE_SYNTAX_POSIX_AWK \ - (RE_SYNTAX_POSIX_EXTENDED | RE_BACKSLASH_ESCAPE_IN_LISTS) - -#define RE_SYNTAX_GREP \ - (RE_BK_PLUS_QM | RE_CHAR_CLASSES \ - | RE_HAT_LISTS_NOT_NEWLINE | RE_INTERVALS \ - | RE_NEWLINE_ALT) - -#define RE_SYNTAX_EGREP \ - (RE_CHAR_CLASSES | RE_CONTEXT_INDEP_ANCHORS \ - | RE_CONTEXT_INDEP_OPS | RE_HAT_LISTS_NOT_NEWLINE \ - | RE_NEWLINE_ALT | RE_NO_BK_PARENS \ - | RE_NO_BK_VBAR) - -#define RE_SYNTAX_POSIX_EGREP \ - (RE_SYNTAX_EGREP | RE_INTERVALS | RE_NO_BK_BRACES) - -/* P1003.2/D11.2, section 4.20.7.1, lines 5078ff. */ -#define RE_SYNTAX_ED RE_SYNTAX_POSIX_BASIC - -#define RE_SYNTAX_SED RE_SYNTAX_POSIX_BASIC - -/* Syntax bits common to both basic and extended POSIX regex syntax. */ -#define _RE_SYNTAX_POSIX_COMMON \ - (RE_CHAR_CLASSES | RE_DOT_NEWLINE | RE_DOT_NOT_NULL \ - | RE_INTERVALS | RE_NO_EMPTY_RANGES) - -#define RE_SYNTAX_POSIX_BASIC \ - (_RE_SYNTAX_POSIX_COMMON | RE_BK_PLUS_QM) - -/* Differs from ..._POSIX_BASIC only in that RE_BK_PLUS_QM becomes - RE_LIMITED_OPS, i.e., \? \+ \| are not recognized. Actually, this - isn't minimal, since other operators, such as \`, aren't disabled. */ -#define RE_SYNTAX_POSIX_MINIMAL_BASIC \ - (_RE_SYNTAX_POSIX_COMMON | RE_LIMITED_OPS) - -#define RE_SYNTAX_POSIX_EXTENDED \ - (_RE_SYNTAX_POSIX_COMMON | RE_CONTEXT_INDEP_ANCHORS \ - | RE_CONTEXT_INDEP_OPS | RE_NO_BK_BRACES \ - | RE_NO_BK_PARENS | RE_NO_BK_VBAR \ - | RE_UNMATCHED_RIGHT_PAREN_ORD) - -/* Differs from ..._POSIX_EXTENDED in that RE_CONTEXT_INVALID_OPS - replaces RE_CONTEXT_INDEP_OPS and RE_NO_BK_REFS is added. */ -#define RE_SYNTAX_POSIX_MINIMAL_EXTENDED \ - (_RE_SYNTAX_POSIX_COMMON | RE_CONTEXT_INDEP_ANCHORS \ - | RE_CONTEXT_INVALID_OPS | RE_NO_BK_BRACES \ - | RE_NO_BK_PARENS | RE_NO_BK_REFS \ - | RE_NO_BK_VBAR | RE_UNMATCHED_RIGHT_PAREN_ORD) -/* [[[end syntaxes]]] */ - -/* Maximum number of duplicates an interval can allow. Some systems - (erroneously) define this in other header files, but we want our - value, so remove any previous define. */ -#ifdef RE_DUP_MAX -#undef RE_DUP_MAX -#endif -#define RE_DUP_MAX ((1 << 15) - 1) - - -/* POSIX `cflags' bits (i.e., information for `regcomp'). */ - -/* If this bit is set, then use extended regular expression syntax. - If not set, then use basic regular expression syntax. */ -#define REG_EXTENDED 1 - -/* If this bit is set, then ignore case when matching. - If not set, then case is significant. */ -#define REG_ICASE (REG_EXTENDED << 1) - -/* If this bit is set, then anchors do not match at newline - characters in the string. - If not set, then anchors do match at newlines. */ -#define REG_NEWLINE (REG_ICASE << 1) - -/* If this bit is set, then report only success or fail in regexec. - If not set, then returns differ between not matching and errors. */ -#define REG_NOSUB (REG_NEWLINE << 1) - - -/* POSIX `eflags' bits (i.e., information for regexec). */ - -/* If this bit is set, then the beginning-of-line operator doesn't match - the beginning of the string (presumably because it's not the - beginning of a line). - If not set, then the beginning-of-line operator does match the - beginning of the string. */ -#define REG_NOTBOL 1 - -/* Like REG_NOTBOL, except for the end-of-line. */ -#define REG_NOTEOL (1 << 1) - - -/* If any error codes are removed, changed, or added, update the - `re_error_msg' table in regex.c. */ -typedef enum -{ - REG_NOERROR = 0, /* Success. */ - REG_NOMATCH, /* Didn't find a match (for regexec). */ - - /* POSIX regcomp return error codes. (In the order listed in the - standard.) */ - REG_BADPAT, /* Invalid pattern. */ - REG_ECOLLATE, /* Not implemented. */ - REG_ECTYPE, /* Invalid character class name. */ - REG_EESCAPE, /* Trailing backslash. */ - REG_ESUBREG, /* Invalid back reference. */ - REG_EBRACK, /* Unmatched left bracket. */ - REG_EPAREN, /* Parenthesis imbalance. */ - REG_EBRACE, /* Unmatched \{. */ - REG_BADBR, /* Invalid contents of \{\}. */ - REG_ERANGE, /* Invalid range end. */ - REG_ESPACE, /* Ran out of memory. */ - REG_BADRPT, /* No preceding re for repetition op. */ - - /* Error codes we've added. */ - REG_EEND, /* Premature end. */ - REG_ESIZE, /* Compiled pattern bigger than 2^16 bytes. */ - REG_ERPAREN /* Unmatched ) or \); not returned from regcomp. */ -} reg_errcode_t; - -/* This data structure represents a compiled pattern. Before calling - the pattern compiler, the fields `buffer', `allocated', `fastmap', - `translate', and `no_sub' can be set. After the pattern has been - compiled, the `re_nsub' field is available. All other fields are - private to the regex routines. */ - -struct re_pattern_buffer -{ -/* [[[begin pattern_buffer]]] */ - /* Space that holds the compiled pattern. It is declared as - `unsigned char *' because its elements are - sometimes used as array indexes. */ - unsigned char *buffer; - - /* Number of bytes to which `buffer' points. */ - unsigned long allocated; - - /* Number of bytes actually used in `buffer'. */ - unsigned long used; - - /* Syntax setting with which the pattern was compiled. */ - reg_syntax_t syntax; - - /* Pointer to a fastmap, if any, otherwise zero. re_search uses - the fastmap, if there is one, to skip over impossible - starting points for matches. */ - char *fastmap; - - /* Either a translate table to apply to all characters before - comparing them, or zero for no translation. The translation - is applied to a pattern when it is compiled and to a string - when it is matched. */ - char *translate; - - /* Number of subexpressions found by the compiler. */ - size_t re_nsub; - - /* Zero if this pattern cannot match the empty string, one else. - Well, in truth it's used only in `re_search_2', to see - whether or not we should use the fastmap, so we don't set - this absolutely perfectly; see `re_compile_fastmap' (the - `duplicate' case). */ - unsigned can_be_null : 1; - - /* If REGS_UNALLOCATED, allocate space in the `regs' structure - for `max (RE_NREGS, re_nsub + 1)' groups. - If REGS_REALLOCATE, reallocate space if necessary. - If REGS_FIXED, use what's there. */ -#define REGS_UNALLOCATED 0 -#define REGS_REALLOCATE 1 -#define REGS_FIXED 2 - unsigned regs_allocated : 2; - - /* Set to zero when `regex_compile' compiles a pattern; set to one - by `re_compile_fastmap' if it updates the fastmap. */ - unsigned fastmap_accurate : 1; - - /* If set, `re_match_2' does not return information about - subexpressions. */ - unsigned no_sub : 1; - - /* If set, a beginning-of-line anchor doesn't match at the - beginning of the string. */ - unsigned not_bol : 1; - - /* Similarly for an end-of-line anchor. */ - unsigned not_eol : 1; - - /* If true, an anchor at a newline matches. */ - unsigned newline_anchor : 1; - -/* [[[end pattern_buffer]]] */ -}; - -typedef struct re_pattern_buffer regex_t; - -/* Type for byte offsets within the string. POSIX mandates this. */ -typedef int regoff_t; - - -/* This is the structure we store register match data in. See - regex.texinfo for a full description of what registers match. */ -struct re_registers -{ - unsigned num_regs; - regoff_t *start; - regoff_t *end; -}; - - -/* If `regs_allocated' is REGS_UNALLOCATED in the pattern buffer, - `re_match_2' returns information about at least this many registers - the first time a `regs' structure is passed. */ -#ifndef RE_NREGS -#define RE_NREGS 30 -#endif - - -/* POSIX specification for registers. Aside from the different names than - `re_registers', POSIX uses an array of structures, instead of a - structure of arrays. */ -typedef struct -{ - regoff_t rm_so; /* Byte offset from string's start to substring's start. */ - regoff_t rm_eo; /* Byte offset from string's start to substring's end. */ -} regmatch_t; - -/* Declarations for routines. */ - -/* To avoid duplicating every routine declaration -- once with a - prototype (if we are ANSI), and once without (if we aren't) -- we - use the following macro to declare argument types. This - unfortunately clutters up the declarations a bit, but I think it's - worth it. */ - -#if __STDC__ - -#define _RE_ARGS(args) args - -#else /* not __STDC__ */ - -#define _RE_ARGS(args) () - -#endif /* not __STDC__ */ - -/* Sets the current default syntax to SYNTAX, and return the old syntax. - You can also simply assign to the `re_syntax_options' variable. */ -extern reg_syntax_t re_set_syntax _RE_ARGS ((reg_syntax_t syntax)); - -/* Compile the regular expression PATTERN, with length LENGTH - and syntax given by the global `re_syntax_options', into the buffer - BUFFER. Return NULL if successful, and an error string if not. */ -extern const char *re_compile_pattern - _RE_ARGS ((const char *pattern, int length, - struct re_pattern_buffer *buffer)); - - -/* Compile a fastmap for the compiled pattern in BUFFER; used to - accelerate searches. Return 0 if successful and -2 if was an - internal error. */ -extern int re_compile_fastmap _RE_ARGS ((struct re_pattern_buffer *buffer)); - - -/* Search in the string STRING (with length LENGTH) for the pattern - compiled into BUFFER. Start searching at position START, for RANGE - characters. Return the starting position of the match, -1 for no - match, or -2 for an internal error. Also return register - information in REGS (if REGS and BUFFER->no_sub are nonzero). */ -extern int re_search - _RE_ARGS ((struct re_pattern_buffer *buffer, const char *string, - int length, int start, int range, struct re_registers *regs)); - - -/* Like `re_search', but search in the concatenation of STRING1 and - STRING2. Also, stop searching at index START + STOP. */ -extern int re_search_2 - _RE_ARGS ((struct re_pattern_buffer *buffer, const char *string1, - int length1, const char *string2, int length2, - int start, int range, struct re_registers *regs, int stop)); - - -/* Like `re_search', but return how many characters in STRING the regexp - in BUFFER matched, starting at position START. */ -extern int re_match - _RE_ARGS ((struct re_pattern_buffer *buffer, const char *string, - int length, int start, struct re_registers *regs)); - - -/* Relates to `re_match' as `re_search_2' relates to `re_search'. */ -extern int re_match_2 - _RE_ARGS ((struct re_pattern_buffer *buffer, const char *string1, - int length1, const char *string2, int length2, - int start, struct re_registers *regs, int stop)); - - -/* Set REGS to hold NUM_REGS registers, storing them in STARTS and - ENDS. Subsequent matches using BUFFER and REGS will use this memory - for recording register information. STARTS and ENDS must be - allocated with malloc, and must each be at least `NUM_REGS * sizeof - (regoff_t)' bytes long. - - If NUM_REGS == 0, then subsequent matches should allocate their own - register data. - - Unless this function is called, the first search or match using - PATTERN_BUFFER will allocate its own register data, without - freeing the old data. */ -extern void re_set_registers - _RE_ARGS ((struct re_pattern_buffer *buffer, struct re_registers *regs, - unsigned num_regs, regoff_t *starts, regoff_t *ends)); - -#ifdef _REGEX_RE_COMP -/* 4.2 bsd compatibility. */ -extern char *re_comp _RE_ARGS ((const char *)); -extern int re_exec _RE_ARGS ((const char *)); -#endif - -/* POSIX compatibility. */ -extern int regcomp _RE_ARGS ((regex_t *preg, const char *pattern, int cflags)); -extern int regexec - _RE_ARGS ((const regex_t *preg, const char *string, size_t nmatch, - regmatch_t pmatch[], int eflags)); -extern size_t regerror - _RE_ARGS ((int errcode, const regex_t *preg, char *errbuf, - size_t errbuf_size)); -extern void regfree _RE_ARGS ((regex_t *preg)); - -#endif /* not __REGEXP_LIBRARY_H__ */ - -/* -Local variables: -make-backup-files: t -version-control: t -trim-versions-without-asking: nil -End: -*/ diff --git a/src/bin/findutils/lib/regexprops.c b/src/bin/findutils/lib/regexprops.c new file mode 100644 index 0000000000..96872811f8 --- /dev/null +++ b/src/bin/findutils/lib/regexprops.c @@ -0,0 +1,505 @@ +/* regexprops.c -- document the properties of the regular expressions + understood by gnulib. + + Copyright 2005, 2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +/* Written by James Youngman, . */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include +#include + +#include "regex.h" +#include "regextype.h" + + +/* Name this program was run with. */ +char *program_name; + +static void output(const char *s, int escape) +{ + fputs(s, stdout); +} + + +static void newline(void) +{ + output("\n", 0); +} + +static void content(const char *s) +{ + output(s, 1); +} + +static void literal(const char *s) +{ + output(s, 0); +} + +static void directive(const char *s) +{ + output(s, 0); +} + +static void enum_item(const char *s) +{ + newline(); + directive("@item "); + literal(s); + newline(); +} +static void table_item(const char *s) +{ + directive("@item"); + newline(); + content(s); + newline(); +} + +static void code(const char *s) +{ + directive("@code{"); + content(s); + directive("}"); +} + +static void begin_subsection(const char *name, + const char *next, + const char *prev, + const char *up) +{ + newline(); + + directive("@node "); + content(name); + content(" regular expression syntax"); + newline(); + + directive("@subsection "); + output("@samp{", 0); + content(name); + output("}", 0); + content(" regular expression syntax"); + newline(); +} + +static void begintable_asis() +{ + newline(); + directive("@table @asis"); + newline(); +} + +static void begintable_markup(char const *markup) +{ + newline(); + directive("@table "); + literal(markup); + newline(); +} + +static void endtable() +{ + newline(); + directive("@end table"); + newline(); +} + +static void beginenum() +{ + newline(); + directive("@enumerate"); + newline(); +} + +static void endenum() +{ + newline(); + directive("@end enumerate"); + newline(); +} + +static void newpara() +{ + content("\n\n"); +} + + +static int describe_regex_syntax(int options) +{ + newpara(); + content("The character @samp{.} matches any single character"); + if ( (options & RE_DOT_NEWLINE) == 0 ) + { + content(" except newline"); + } + if (options & RE_DOT_NOT_NULL) + { + if ( (options & RE_DOT_NEWLINE) == 0 ) + content(" and"); + else + content(" except"); + + content(" the null character"); + } + content(". "); + newpara(); + + if (!(options & RE_LIMITED_OPS)) + { + begintable_markup("@samp"); + if (options & RE_BK_PLUS_QM) + { + enum_item("\\+"); + content("indicates that the regular expression should match one" + " or more occurrences of the previous atom or regexp. "); + enum_item("\\?"); + content("indicates that the regular expression should match zero" + " or one occurrence of the previous atom or regexp. "); + enum_item("+ and ? "); + content("match themselves. "); + } + else + { + enum_item("+"); + content("indicates that the regular expression should match one" + " or more occurrences of the previous atom or regexp. "); + enum_item("?"); + content("indicates that the regular expression should match zero" + " or one occurrence of the previous atom or regexp. "); + enum_item("\\+"); + literal("matches a @samp{+}"); + enum_item("\\?"); + literal("matches a @samp{?}. "); + } + endtable(); + } + + newpara(); + + content("Bracket expressions are used to match ranges of characters. "); + literal("Bracket expressions where the range is backward, for example @samp{[z-a]}, are "); + if (options & RE_NO_EMPTY_RANGES) + content("invalid"); + else + content("ignored"); + content(". "); + + if (options & RE_BACKSLASH_ESCAPE_IN_LISTS) + literal("Within square brackets, @samp{\\} can be used to quote " + "the following character. "); + else + literal("Within square brackets, @samp{\\} is taken literally. "); + + if (options & RE_CHAR_CLASSES) + content("Character classes are supported; for example " + "@samp{[[:digit:]]} will match a single decimal digit. "); + else + literal("Character classes are not supported, so for example " + "you would need to use @samp{[0-9]} " + "instead of @samp{[[:digit:]]}. "); + + if (options & RE_HAT_LISTS_NOT_NEWLINE) + { + literal("Non-matching lists @samp{[^@dots{}]} do not ever match newline. "); + } + newpara(); + if (options & RE_NO_GNU_OPS) + { + content("GNU extensions are not supported and so " + "@samp{\\w}, @samp{\\W}, @samp{\\<}, @samp{\\>}, @samp{\\b}, @samp{\\B}, @samp{\\`}, and @samp{\\'} " + "match " + "@samp{w}, @samp{W}, @samp{<}, @samp{>}, @samp{b}, @samp{B}, @samp{`}, and @samp{'} respectively. "); + } + else + { + content("GNU extensions are supported:"); + beginenum(); + enum_item("@samp{\\w} matches a character within a word"); + enum_item("@samp{\\W} matches a character which is not within a word"); + enum_item("@samp{\\<} matches the beginning of a word"); + enum_item("@samp{\\>} matches the end of a word"); + enum_item("@samp{\\b} matches a word boundary"); + enum_item("@samp{\\B} matches characters which are not a word boundary"); + enum_item("@samp{\\`} matches the beginning of the whole input"); + enum_item("@samp{\\'} matches the end of the whole input"); + endenum(); + } + + newpara(); + + + if (options & RE_NO_BK_PARENS) + { + literal("Grouping is performed with parentheses @samp{()}. "); + + if (options & RE_UNMATCHED_RIGHT_PAREN_ORD) + literal("An unmatched @samp{)} matches just itself. "); + } + else + { + literal("Grouping is performed with backslashes followed by parentheses @samp{\\(}, @samp{\\)}. "); + } + + if (options & RE_NO_BK_REFS) + { + content("A backslash followed by a digit matches that digit. "); + } + else + { + literal("A backslash followed by a digit acts as a back-reference and matches the same thing as the previous grouped expression indicated by that number. For example @samp{\\2} matches the second group expression. The order of group expressions is determined by the position of their opening parenthesis "); + if (options & RE_NO_BK_PARENS) + literal("@samp{(}"); + else + literal("@samp{\\(}"); + content(". "); + } + + + newpara(); + if (!(options & RE_LIMITED_OPS)) + { + if (options & RE_NO_BK_VBAR) + literal("The alternation operator is @samp{|}. "); + else + literal("The alternation operator is @samp{\\|}. "); + } + newpara(); + + if (options & RE_CONTEXT_INDEP_ANCHORS) + { + literal("The characters @samp{^} and @samp{$} always represent the beginning and end of a string respectively, except within square brackets. Within brackets, @samp{^} can be used to invert the membership of the character class being specified. "); + } + else + { + literal("The character @samp{^} only represents the beginning of a string when it appears:"); + beginenum(); + enum_item("\nAt the beginning of a regular expression"); + enum_item("After an open-group, signified by "); + if (options & RE_NO_BK_PARENS) + { + literal("@samp{(}"); + } + else + { + literal("@samp{\\(}"); + } + newline(); + if (!(options & RE_LIMITED_OPS)) + { + if (options & RE_NEWLINE_ALT) + enum_item("After a newline"); + + if (options & RE_NO_BK_VBAR ) + enum_item("After the alternation operator @samp{|}"); + else + enum_item("After the alternation operator @samp{\\|}"); + } + endenum(); + + newpara(); + literal("The character @samp{$} only represents the end of a string when it appears:"); + beginenum(); + enum_item("At the end of a regular expression"); + enum_item("Before a close-group, signified by "); + if (options & RE_NO_BK_PARENS) + { + literal("@samp{)}"); + } + else + { + literal("@samp{\\)}"); + } + if (!(options & RE_LIMITED_OPS)) + { + if (options & RE_NEWLINE_ALT) + enum_item("Before a newline"); + + if (options & RE_NO_BK_VBAR) + enum_item("Before the alternation operator @samp{|}"); + else + enum_item("Before the alternation operator @samp{\\|}"); + } + endenum(); + } + newpara(); + if (!(options & RE_LIMITED_OPS) ) + { + if ((options & RE_CONTEXT_INDEP_OPS) + && !(options & RE_CONTEXT_INVALID_OPS)) + { + literal("The characters @samp{*}, @samp{+} and @samp{?} are special anywhere in a regular expression. "); + } + else + { + if (options & RE_BK_PLUS_QM) + literal("@samp{\\*}, @samp{\\+} and @samp{\\?} "); + else + literal("@samp{*}, @samp{+} and @samp{?} "); + + if (options & RE_CONTEXT_INVALID_OPS) + { + content("are special at any point in a regular expression except the following places, where they are not allowed:"); + } + else + { + content("are special at any point in a regular expression except:"); + } + + beginenum(); + enum_item("At the beginning of a regular expression"); + enum_item("After an open-group, signified by "); + if (options & RE_NO_BK_PARENS) + { + literal("@samp{(}"); + } + else + { + literal("@samp{\\(}"); + } + if (!(options & RE_LIMITED_OPS)) + { + if (options & RE_NEWLINE_ALT) + enum_item("After a newline"); + + if (options & RE_NO_BK_VBAR) + enum_item("After the alternation operator @samp{|}"); + else + enum_item("After the alternation operator @samp{\\|}"); + } + endenum(); + } + } + + + newpara(); + if (options & RE_INTERVALS) + { + if (options & RE_NO_BK_BRACES) + { + literal("Intervals are specified by @samp{@{} and @samp{@}}. "); + if (options & RE_INVALID_INTERVAL_ORD) + { + literal("Invalid intervals are treated as literals, for example @samp{a@{1} is treated as @samp{a\\@{1}"); + } + else + { + literal("Invalid intervals such as @samp{a@{1z} are not accepted. "); + } + } + else + { + literal("Intervals are specified by @samp{\\@{} and @samp{\\@}}. "); + if (options & RE_INVALID_INTERVAL_ORD) + { + literal("Invalid intervals are treated as literals, for example @samp{a\\@{1} is treated as @samp{a@{1}"); + } + else + { + literal("Invalid intervals such as @samp{a\\@{1z} are not accepted. "); + } + } + + } + + newpara(); + if (options & RE_NO_POSIX_BACKTRACKING) + { + content("Matching succeeds as soon as the whole pattern is matched, meaning that the result may not be the longest possible match. "); + } + else + { + content("The longest possible match is returned; this applies to the regular expression as a whole and (subject to this constraint) to subexpressions within groups. "); + } + newpara(); +} + + + +static int menu() +{ + int i, options; + const char *name; + + output("@menu\n", 0); + for (i=0; + options = get_regex_type_flags(i), + name=get_regex_type_name(i); + ++i) + { + output("* ", 0); + output(name, 0); + content(" regular expression syntax"); + output("::", 0); + newline(); + } + output("@end menu\n", 0); +} + + +static int describe_all(const char *up) +{ + const char *name, *next, *previous; + int options; + int i, parent; + + menu(); + + previous = ""; + + for (i=0; + options = get_regex_type_flags(i), + name=get_regex_type_name(i); + ++i) + { + next = get_regex_type_name(i+1); + if (NULL == next) + next = ""; + begin_subsection(name, next, previous, up); + parent = get_regex_type_synonym(i); + if (parent >= 0) + { + content("This is a synonym for "); + content(get_regex_type_name(parent)); + content("."); + } + else + { + describe_regex_syntax(options); + } + previous = name; + } +} + + + +int main (int argc, char *argv[]) +{ + const char *up = ""; + program_name = argv[0]; + + if (argc > 1) + up = argv[1]; + + describe_all(up); + return 0; +} diff --git a/src/bin/findutils/lib/regextype.c b/src/bin/findutils/lib/regextype.c new file mode 100644 index 0000000000..eef18d5e34 --- /dev/null +++ b/src/bin/findutils/lib/regextype.c @@ -0,0 +1,157 @@ + +/* regextype.c -- Decode the name of a regular expression syntax into am + option name. + + Copyright 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +/* Written by James Youngman, . */ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#include + +#include "regextype.h" +#include "regex.h" +#include "quote.h" +#include "quotearg.h" +#include "xalloc.h" +#include "error.h" + + +#if ENABLE_NLS +# include +# define _(Text) gettext (Text) +#else +# define _(Text) Text +#endif +#ifdef gettext_noop +# define N_(String) gettext_noop (String) +#else +/* See locate.c for explanation as to why not use (String) */ +# define N_(String) String +#endif + + + +struct tagRegexTypeMap +{ + char *name; + int option_val; +}; + +struct tagRegexTypeMap regex_map[] = + { +#ifdef FINDUTILS + { "findutils-default", RE_SYNTAX_EMACS|RE_DOT_NEWLINE }, +#endif + { "awk", RE_SYNTAX_AWK }, + { "egrep", RE_SYNTAX_EGREP }, +#ifndef FINDUTILS + { "ed", RE_SYNTAX_ED }, +#endif + { "emacs", RE_SYNTAX_EMACS }, + { "gnu-awk", RE_SYNTAX_GNU_AWK }, + { "grep", RE_SYNTAX_GREP }, + { "posix-awk", RE_SYNTAX_POSIX_AWK }, + { "posix-basic", RE_SYNTAX_POSIX_BASIC }, + { "posix-egrep", RE_SYNTAX_POSIX_EGREP }, + { "posix-extended", RE_SYNTAX_POSIX_EXTENDED }, +#ifndef FINDUTILS + { "posix-minimal-basic", RE_SYNTAX_POSIX_MINIMAL_BASIC }, + { "sed", RE_SYNTAX_SED }, + /* ,{ "posix-common", _RE_SYNTAX_POSIX_COMMON } */ +#endif + }; +enum { N_REGEX_MAP_ENTRIES = sizeof(regex_map)/sizeof(regex_map[0]) }; + +int +get_regex_type(const char *s) +{ + unsigned i; + size_t msglen; + char *buf, *p; + + msglen = 0u; + for (i=0u; i 0u) + { + strcpy(p, ", "); + p += 2; + } + p += sprintf(p, "%s", quote(regex_map[i].name)); + } + + error(1, 0, _("Unknown regular expression type %s; valid types are %s."), + quote(s), + buf); + /*NOTREACHED*/ + return -1; +} + + +const char * +get_regex_type_name(int ix) +{ + if (ix < N_REGEX_MAP_ENTRIES) + return regex_map[ix].name; + else + return NULL; +} + +int +get_regex_type_flags(int ix) +{ + if (ix < N_REGEX_MAP_ENTRIES) + return regex_map[ix].option_val; + else + return -1; +} + + +int get_regex_type_synonym(int ix) +{ + unsigned i; + int flags; + + if (ix >= N_REGEX_MAP_ENTRIES) + return -1; + + flags = regex_map[ix].option_val; + for (i=0u; i. +*/ +/* Written by James Youngman . + */ + +int get_regex_type(const char *s); + + +const char * get_regex_type_name(int ix); +int get_regex_type_flags(int ix); +int get_regex_type_synonym(int ix); diff --git a/src/bin/findutils/lib/savedir.c b/src/bin/findutils/lib/savedir.c deleted file mode 100644 index 1992cf55bf..0000000000 --- a/src/bin/findutils/lib/savedir.c +++ /dev/null @@ -1,131 +0,0 @@ -/* savedir.c -- save the list of files in a directory in a string - Copyright (C) 1990 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -/* Written by David MacKenzie . */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include - -#ifdef HAVE_UNISTD_H -#include -#endif - -#if HAVE_DIRENT_H -# include -# define NAMLEN(dirent) strlen((dirent)->d_name) -#else -# define dirent direct -# define NAMLEN(dirent) (dirent)->d_namlen -# if HAVE_SYS_NDIR_H -# include -# endif -# if HAVE_SYS_DIR_H -# include -# endif -# if HAVE_NDIR_H -# include -# endif -#endif - -#ifdef CLOSEDIR_VOID -/* Fake a return value. */ -#define CLOSEDIR(d) (closedir (d), 0) -#else -#define CLOSEDIR(d) closedir (d) -#endif - -#ifdef STDC_HEADERS -#include -#include -#else -char *malloc (); -char *realloc (); -#endif -#ifndef NULL -#define NULL 0 -#endif - -char *stpcpy (); - -/* Return a freshly allocated string containing the filenames - in directory DIR, separated by '\0' characters; - the end is marked by two '\0' characters in a row. - NAME_SIZE is the number of bytes to initially allocate - for the string; it will be enlarged as needed. - Return NULL if DIR cannot be opened or if out of memory. */ - -char * -savedir (dir, name_size) - char *dir; - unsigned name_size; -{ - DIR *dirp; - struct dirent *dp; - char *name_space; - char *namep; - - dirp = opendir (dir); - if (dirp == NULL) - return NULL; - - name_space = (char *) malloc (name_size); - if (name_space == NULL) - { - closedir (dirp); - return NULL; - } - namep = name_space; - - while ((dp = readdir (dirp)) != NULL) - { - /* Skip "." and ".." (some NFS filesystems' directories lack them). */ - if (dp->d_name[0] != '.' - || (dp->d_name[1] != '\0' - && (dp->d_name[1] != '.' || dp->d_name[2] != '\0'))) - { - unsigned size_needed = (namep - name_space) + NAMLEN (dp) + 2; - - if (size_needed > name_size) - { - char *new_name_space; - - while (size_needed > name_size) - name_size += 1024; - - new_name_space = realloc (name_space, name_size); - if (new_name_space == NULL) - { - closedir (dirp); - return NULL; - } - namep += new_name_space - name_space; - name_space = new_name_space; - } - namep = stpcpy (namep, dp->d_name) + 1; - } - } - *namep = '\0'; - if (CLOSEDIR (dirp)) - { - free (name_space); - return NULL; - } - return name_space; -} diff --git a/src/bin/findutils/lib/savedirinfo.c b/src/bin/findutils/lib/savedirinfo.c new file mode 100644 index 0000000000..b37cd6ed79 --- /dev/null +++ b/src/bin/findutils/lib/savedirinfo.c @@ -0,0 +1,386 @@ +/* savedirinfo.c -- Save the list of files in a directory, with additional information. + + Copyright 1990, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005 Free + Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +/* Written by James Youngman, . */ +/* Derived from savedir.c, written by David MacKenzie . */ + +#if HAVE_CONFIG_H +# include +#endif + +#if HAVE_SYS_STAT_H +# include +#endif + +#if HAVE_SYS_TYPES_H +# include +#endif + +/* The presence of unistd.h is assumed by gnulib these days, so we + * might as well assume it too. + */ +#include + +#include + +#if HAVE_DIRENT_H +# include +#else +# define dirent direct +# if HAVE_SYS_NDIR_H +# include +# endif +# if HAVE_SYS_DIR_H +# include +# endif +# if HAVE_NDIR_H +# include +# endif +#endif + +#ifdef CLOSEDIR_VOID +/* Fake a return value. */ +# define CLOSEDIR(d) (closedir (d), 0) +#else +# define CLOSEDIR(d) closedir (d) +#endif + +#include +#include +#include + +#include "xalloc.h" +#include "extendbuf.h" +#include "savedirinfo.h" + +/* In order to use struct dirent.d_type, it has to be enabled on the + * configure command line, and we have to have a d_type member in + * 'struct dirent'. + */ +#if !defined(USE_STRUCT_DIRENT_D_TYPE) +/* Not enabled, hence pretend it is absent. */ +#undef HAVE_STRUCT_DIRENT_D_TYPE +#endif +#if !defined(HAVE_STRUCT_DIRENT_D_TYPE) +/* Not present, so cannot use it. */ +#undef USE_STRUCT_DIRENT_D_TYPE +#endif + + +#if defined(HAVE_STRUCT_DIRENT_D_TYPE) && defined(USE_STRUCT_DIRENT_D_TYPE) +/* Convert the value of struct dirent.d_type into a value for + * struct stat.st_mode (at least the file type bits), or zero + * if the type is DT_UNKNOWN or is a value we don't know about. + */ +static mode_t +type_to_mode(unsigned type) +{ + switch (type) + { +#ifdef DT_FIFO + case DT_FIFO: return S_IFIFO; +#endif +#ifdef DT_CHR + case DT_CHR: return S_IFCHR; +#endif +#ifdef DT_DIR + case DT_DIR: return S_IFDIR; +#endif +#ifdef DT_BLK + case DT_BLK: return S_IFBLK; +#endif +#ifdef DT_REG + case DT_REG: return S_IFREG; +#endif +#ifdef DT_LNK + case DT_LNK: return S_IFLNK; +#endif +#ifdef DT_SOCK + case DT_SOCK: return S_IFSOCK; +#endif + default: + return 0; /* Unknown. */ + } +} + +#endif + +struct new_savedir_direntry_internal +{ + int flags; /* from SaveDirDataFlags */ + mode_t type_info; + size_t buffer_offset; +}; + + + +static int +savedir_cmp(const void *p1, const void *p2) +{ + const struct savedir_direntry *de1, *de2; + de1 = p1; + de2 = p2; + return strcmp(de1->name, de2->name); /* POSIX order, not locale order. */ +} + + +static struct savedir_direntry* +convertentries(const struct savedir_dirinfo *info, + struct new_savedir_direntry_internal *internal) +{ + char *p = info->buffer; + struct savedir_direntry *result; + int n =info->size; + int i; + + + result = xmalloc(sizeof(*result) * info->size); + + for (i=0; ibuffer = NULL; + result->size = 0u; + result->entries = NULL; + internal = NULL; + + while ((dp = readdir (dirp)) != NULL) + { + /* Skip "", ".", and "..". "" is returned by at least one buggy + implementation: Solaris 2.4 readdir on NFS file systems. */ + char const *entry = dp->d_name; + if (entry[entry[0] != '.' ? 0 : entry[1] != '.' ? 1 : 2] != '\0') + { + /* Remember the name. */ + size_t entry_size = strlen (entry) + 1; + result->buffer = extendbuf(result->buffer, namebuf_used+entry_size, &namebuf_allocated); + memcpy ((result->buffer) + namebuf_used, entry, entry_size); + + /* Remember the other stuff. */ + internal = extendbuf(internal, (1+result->size)*sizeof(*internal), &entrybuf_allocated); + internal[result->size].flags = 0; + +#if defined(HAVE_STRUCT_DIRENT_D_TYPE) && defined(USE_STRUCT_DIRENT_D_TYPE) + internal[result->size].type_info = type_to_mode(dp->d_type); + if (dp->d_type != DT_UNKNOWN) + internal[result->size].flags |= SavedirHaveFileType; +#else + internal[result->size].type_info = 0; +#endif + internal[result->size].buffer_offset = namebuf_used; + + /* Prepare for the next iteration */ + ++(result->size); + namebuf_used += entry_size; + } + } + + result->buffer = extendbuf(result->buffer, namebuf_used+1, &namebuf_allocated); + result->buffer[namebuf_used] = '\0'; + + /* convert the result to its externally-usable form. */ + result->entries = convertentries(result, internal); + free(internal); + internal = NULL; + + + if (flags & SavedirSort) + { + qsort(result->entries, + result->size, sizeof(*result->entries), + savedir_cmp); + } + + + save_errno = errno; + if (CLOSEDIR (dirp) != 0) + save_errno = errno; + if (save_errno != 0) + { + free (result->buffer); + free (result); + errno = save_errno; + return NULL; + } + + return result; +} + +void free_dirinfo(struct savedir_dirinfo *p) +{ + free(p->entries); + p->entries = NULL; + free(p->buffer); + p->buffer = NULL; + free(p); +} + + + +static char * +new_savedirinfo (const char *dir, struct savedir_extrainfo **extra) +{ + struct savedir_dirinfo *p = xsavedir(dir, SavedirSort); + char *buf, *s; + size_t bufbytes = 0; + int i; + + if (p) + { + struct savedir_extrainfo *pex = xmalloc(p->size * sizeof(*extra)); + for (i=0; isize; ++i) + { + bufbytes += strlen(p->entries[i].name); + ++bufbytes; /* the \0 */ + + pex[i].type_info = p->entries[i].type_info; + } + + s = buf = xmalloc(bufbytes+1); + for (i=0; isize; ++i) + { + size_t len = strlen(p->entries[i].name); + memcpy(s, p->entries[i].name, len); + s += len; + *s = 0; /* Place a NUL */ + ++s; /* Skip the NUL. */ + } + *s = 0; /* final (doubled) terminating NUL */ + + if (extra) + *extra = pex; + else + free (pex); + return buf; + } + else + { + return NULL; + } +} + + +#if 0 +/* Return a freshly allocated string containing the filenames + in directory DIR, separated by '\0' characters; + the end is marked by two '\0' characters in a row. + Return NULL (setting errno) if DIR cannot be opened, read, or closed. */ + +static char * +old_savedirinfo (const char *dir, struct savedir_extrainfo **extra) +{ + DIR *dirp; + struct dirent *dp; + char *name_space; + size_t namebuf_allocated = 0u, namebuf_used = 0u; +#if defined(HAVE_STRUCT_DIRENT_D_TYPE) && defined(USE_STRUCT_DIRENT_D_TYPE) + size_t extra_allocated = 0u, extra_used = 0u; + struct savedir_extrainfo *info = NULL; +#endif + int save_errno; + + if (extra) + *extra = NULL; + + dirp = opendir (dir); + if (dirp == NULL) + return NULL; + + errno = 0; + name_space = NULL; + while ((dp = readdir (dirp)) != NULL) + { + /* Skip "", ".", and "..". "" is returned by at least one buggy + implementation: Solaris 2.4 readdir on NFS file systems. */ + char const *entry = dp->d_name; + if (entry[entry[0] != '.' ? 0 : entry[1] != '.' ? 1 : 2] != '\0') + { + /* Remember the name. */ + size_t entry_size = strlen (entry) + 1; + name_space = extendbuf(name_space, namebuf_used+entry_size, &namebuf_allocated); + memcpy (name_space + namebuf_used, entry, entry_size); + namebuf_used += entry_size; + + +#if defined(HAVE_STRUCT_DIRENT_D_TYPE) && defined(USE_STRUCT_DIRENT_D_TYPE) + /* Remember the type. */ + if (extra) + { + info = extendbuf(info, + (extra_used+1) * sizeof(struct savedir_dirinfo), + &extra_allocated); + info[extra_used].type_info = type_to_mode(dp->d_type); + ++extra_used; + } +#endif + } + } + + name_space = extendbuf(name_space, namebuf_used+1, &namebuf_allocated); + name_space[namebuf_used] = '\0'; + + save_errno = errno; + if (CLOSEDIR (dirp) != 0) + save_errno = errno; + if (save_errno != 0) + { + free (name_space); + errno = save_errno; + return NULL; + } + +#if defined(HAVE_STRUCT_DIRENT_D_TYPE) && defined(USE_STRUCT_DIRENT_D_TYPE) + if (extra && info) + *extra = info; +#endif + + return name_space; +} +#endif + + +char * +savedirinfo (const char *dir, struct savedir_extrainfo **extra) +{ + return new_savedirinfo(dir, extra); +} diff --git a/src/bin/findutils/lib/savedirinfo.h b/src/bin/findutils/lib/savedirinfo.h new file mode 100644 index 0000000000..d915de64f6 --- /dev/null +++ b/src/bin/findutils/lib/savedirinfo.h @@ -0,0 +1,72 @@ +/* Save the list of files in a directory, with additional information. + + Copyright 1997, 1999, 2001, 2003, 2005 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +/* Written by James Youngman . + * Based on savedir.h by David MacKenzie . + */ + +#if !defined SAVEDIRINFO_H_ +# define SAVEDIRINFO_H_ + + +typedef enum tagSaveDirControlFlags + { + SavedirSort = 1 + } +SaveDirControlFlags; + + +typedef enum tagSaveDirDataFlags + { + SavedirHaveFileType = 1 + } +SaveDirDataFlags; + + +/* We keep the name and the type in a structure together + * to allow us to sort them together. + */ +struct savedir_direntry +{ + int flags; /* from SaveDirDataFlags */ + char *name; /* the name of the directory entry */ + mode_t type_info; /* the type (or zero if unknown) */ +}; + +struct savedir_dirinfo +{ + char *buffer; /* The names are stored here. */ + size_t size; /* The total number of results. */ + struct savedir_direntry *entries; /* The results themselves */ +}; + + +struct savedir_extrainfo +{ + mode_t type_info; +}; + +/* savedirinfo() is the old interface. */ +char *savedirinfo (const char *dir, struct savedir_extrainfo **extra); + +/* savedir() is the 'new' interface, but the function has the same name + * as the function from findutils 4.1.7 and 4.1.20. + */ +struct savedir_dirinfo * xsavedir(const char *dir, int flags); +void free_dirinfo(struct savedir_dirinfo *p); + +#endif diff --git a/src/bin/findutils/lib/stpcpy.c b/src/bin/findutils/lib/stpcpy.c deleted file mode 100644 index 5ca0a2e30c..0000000000 --- a/src/bin/findutils/lib/stpcpy.c +++ /dev/null @@ -1,32 +0,0 @@ -/* stpcpy.c -- copy a string and return pointer to end of new string - Copyright (C) 1989, 1990 Free Software Foundation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -/* Copy SRC to DEST, returning the address of the terminating '\0' in DEST. */ - -char * -stpcpy (dest, src) - char *dest; - const char *src; -{ - while ((*dest++ = *src++) != '\0') - /* Do nothing. */ ; - return dest - 1; -} diff --git a/src/bin/findutils/lib/strdup.c b/src/bin/findutils/lib/strdup.c deleted file mode 100644 index 1d60f13948..0000000000 --- a/src/bin/findutils/lib/strdup.c +++ /dev/null @@ -1,43 +0,0 @@ -/* strdup.c -- return a newly allocated copy of a string - Copyright (C) 1990 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#ifdef STDC_HEADERS -#include -#include -#else -char *malloc (); -char *strcpy (); -#endif - -/* Return a newly allocated copy of STR, - or 0 if out of memory. */ - -char * -strdup (str) - const char *str; -{ - char *newstr; - - newstr = (char *) malloc (strlen (str) + 1); - if (newstr) - strcpy (newstr, str); - return newstr; -} diff --git a/src/bin/findutils/lib/strftime.c b/src/bin/findutils/lib/strftime.c deleted file mode 100644 index 484852a72d..0000000000 --- a/src/bin/findutils/lib/strftime.c +++ /dev/null @@ -1,469 +0,0 @@ -/* strftime - custom formatting of date and/or time - Copyright (C) 1989, 1991, 1992 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -/* Note: this version of strftime lacks locale support, - but it is standalone. - - Performs `%' substitutions similar to those in printf. Except - where noted, substituted fields have a fixed size; numeric fields are - padded if necessary. Padding is with zeros by default; for fields - that display a single number, padding can be changed or inhibited by - following the `%' with one of the modifiers described below. Unknown - field specifiers are copied as normal characters. All other - characters are copied to the output without change. - - Supports a superset of the ANSI C field specifiers. - - Literal character fields: - % % - n newline - t tab - - Numeric modifiers (a nonstandard extension): - - do not pad the field - _ pad the field with spaces - - Time fields: - %H hour (00..23) - %I hour (01..12) - %k hour ( 0..23) - %l hour ( 1..12) - %M minute (00..59) - %p locale's AM or PM - %r time, 12-hour (hh:mm:ss [AP]M) - %R time, 24-hour (hh:mm) - %s time in seconds since 00:00:00, Jan 1, 1970 (a nonstandard extension) - %S second (00..61) - %T time, 24-hour (hh:mm:ss) - %X locale's time representation (%H:%M:%S) - %Z time zone (EDT), or nothing if no time zone is determinable - - Date fields: - %a locale's abbreviated weekday name (Sun..Sat) - %A locale's full weekday name, variable length (Sunday..Saturday) - %b locale's abbreviated month name (Jan..Dec) - %B locale's full month name, variable length (January..December) - %c locale's date and time (Sat Nov 04 12:02:33 EST 1989) - %C century (00..99) - %d day of month (01..31) - %e day of month ( 1..31) - %D date (mm/dd/yy) - %h same as %b - %j day of year (001..366) - %m month (01..12) - %U week number of year with Sunday as first day of week (00..53) - %w day of week (0..6) - %W week number of year with Monday as first day of week (00..53) - %x locale's date representation (mm/dd/yy) - %y last two digits of year (00..99) - %Y year (1970...) - - David MacKenzie */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include -#include -#if defined(TM_IN_SYS_TIME) || (!defined(HAVE_TM_ZONE) && !defined(HAVE_TZNAME)) -#include -#else -#include -#endif - -#ifndef STDC_HEADERS -time_t mktime (); -#endif - -#if defined(HAVE_TZNAME) -extern char *tzname[2]; -#endif - -/* Types of padding for numbers in date and time. */ -enum padding -{ - none, blank, zero -}; - -static char const* const days[] = -{ - "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" -}; - -static char const * const months[] = -{ - "January", "February", "March", "April", "May", "June", - "July", "August", "September", "October", "November", "December" -}; - -/* Add character C to STRING and increment LENGTH, - unless LENGTH would exceed MAX. */ - -#define add_char(c) \ - do \ - { \ - if (length + 1 <= max) \ - string[length++] = (c); \ - } \ - while (0) - -/* Add a 2 digit number to STRING, padding if specified. - Return the number of characters added, up to MAX. */ - -static int -add_num2 (string, num, max, pad) - char *string; - int num; - int max; - enum padding pad; -{ - int top = num / 10; - int length = 0; - - if (top == 0 && pad == blank) - add_char (' '); - else if (top != 0 || pad == zero) - add_char (top + '0'); - add_char (num % 10 + '0'); - return length; -} - -/* Add a 3 digit number to STRING, padding if specified. - Return the number of characters added, up to MAX. */ - -static int -add_num3 (string, num, max, pad) - char *string; - int num; - int max; - enum padding pad; -{ - int top = num / 100; - int mid = (num - top * 100) / 10; - int length = 0; - - if (top == 0 && pad == blank) - add_char (' '); - else if (top != 0 || pad == zero) - add_char (top + '0'); - if (mid == 0 && top == 0 && pad == blank) - add_char (' '); - else if (mid != 0 || top != 0 || pad == zero) - add_char (mid + '0'); - add_char (num % 10 + '0'); - return length; -} - -/* Like strncpy except return the number of characters copied. */ - -static int -add_str (to, from, max) - char *to; - const char *from; - int max; -{ - int i; - - for (i = 0; from[i] && i <= max; ++i) - to[i] = from[i]; - return i; -} - -static int -add_num_time_t (string, max, num) - char *string; - int max; - time_t num; -{ - /* This buffer is large enough to hold the character representation - (including the trailing NUL) of any unsigned decimal quantity - whose binary representation fits in 128 bits. */ - char buf[40]; - int length; - - if (sizeof (num) > 16) - abort (); - sprintf (buf, "%lu", (unsigned long) num); - length = add_str (string, buf, max); - return length; -} - -/* Return the week in the year of the time in TM, with the weeks - starting on Sundays. */ - -static int -sun_week (tm) - struct tm *tm; -{ - int dl; - - /* Set `dl' to the day in the year of the last day of the week previous - to the one containing the day specified in TM. If the day specified - in TM is in the first week of the year, `dl' will be negative or 0. - Otherwise, calculate the number of complete weeks before our week - (dl / 7) and add any partial week at the start of the year (dl % 7). */ - dl = tm->tm_yday - tm->tm_wday; - return dl <= 0 ? 0 : dl / 7 + (dl % 7 != 0); -} - -/* Return the week in the year of the time in TM, with the weeks - starting on Mondays. */ - -static int -mon_week (tm) - struct tm *tm; -{ - int dl, wday; - - if (tm->tm_wday == 0) - wday = 6; - else - wday = tm->tm_wday - 1; - dl = tm->tm_yday - wday; - return dl <= 0 ? 0 : dl / 7 + (dl % 7 != 0); -} - -#if !defined(HAVE_TM_ZONE) && !defined(HAVE_TZNAME) -char * -zone_name (tp) - struct tm *tp; -{ - char *timezone (); - struct timeval tv; - struct timezone tz; - - gettimeofday (&tv, &tz); - return timezone (tz.tz_minuteswest, tp->tm_isdst); -} -#endif - -/* Format the time given in TM according to FORMAT, and put the - results in STRING. - Return the number of characters (not including terminating null) - that were put into STRING, or 0 if the length would have - exceeded MAX. */ - -size_t -strftime (string, max, format, tm) - char *string; - size_t max; - const char *format; - const struct tm *tm; -{ - enum padding pad; /* Type of padding to apply. */ - size_t length = 0; /* Characters put in STRING so far. */ - - for (; *format && length < max; ++format) - { - if (*format != '%') - add_char (*format); - else - { - ++format; - /* Modifiers: */ - if (*format == '-') - { - pad = none; - ++format; - } - else if (*format == '_') - { - pad = blank; - ++format; - } - else - pad = zero; - - switch (*format) - { - /* Literal character fields: */ - case 0: - case '%': - add_char ('%'); - break; - case 'n': - add_char ('\n'); - break; - case 't': - add_char ('\t'); - break; - default: - add_char (*format); - break; - - /* Time fields: */ - case 'H': - case 'k': - length += - add_num2 (&string[length], tm->tm_hour, max - length, - *format == 'H' ? pad : blank); - break; - case 'I': - case 'l': - { - int hour12; - - if (tm->tm_hour == 0) - hour12 = 12; - else if (tm->tm_hour > 12) - hour12 = tm->tm_hour - 12; - else - hour12 = tm->tm_hour; - length += - add_num2 (&string[length], hour12, max - length, - *format == 'I' ? pad : blank); - } - break; - case 'M': - length += - add_num2 (&string[length], tm->tm_min, max - length, pad); - break; - case 'p': - if (tm->tm_hour < 12) - add_char ('A'); - else - add_char ('P'); - add_char ('M'); - break; - case 'r': - length += - strftime (&string[length], max - length, "%I:%M:%S %p", tm); - break; - case 'R': - length += - strftime (&string[length], max - length, "%H:%M", tm); - break; - - case 's': - { - struct tm writable_tm; - writable_tm = *tm; - length += add_num_time_t (&string[length], max - length, - mktime (&writable_tm)); - } - break; - - case 'S': - length += - add_num2 (&string[length], tm->tm_sec, max - length, pad); - break; - case 'T': - length += - strftime (&string[length], max - length, "%H:%M:%S", tm); - break; - case 'X': - length += - strftime (&string[length], max - length, "%H:%M:%S", tm); - break; - case 'Z': -#ifdef HAVE_TM_ZONE - length += add_str (&string[length], tm->tm_zone, max - length); -#else -#ifdef HAVE_TZNAME - if (tm->tm_isdst && tzname[1] && *tzname[1]) - length += add_str (&string[length], tzname[1], max - length); - else - length += add_str (&string[length], tzname[0], max - length); -#else - length += add_str (&string[length], zone_name (tm), max - length); -#endif -#endif - break; - - /* Date fields: */ - case 'a': - add_char (days[tm->tm_wday][0]); - add_char (days[tm->tm_wday][1]); - add_char (days[tm->tm_wday][2]); - break; - case 'A': - length += - add_str (&string[length], days[tm->tm_wday], max - length); - break; - case 'b': - case 'h': - add_char (months[tm->tm_mon][0]); - add_char (months[tm->tm_mon][1]); - add_char (months[tm->tm_mon][2]); - break; - case 'B': - length += - add_str (&string[length], months[tm->tm_mon], max - length); - break; - case 'c': - length += - strftime (&string[length], max - length, - "%a %b %d %H:%M:%S %Z %Y", tm); - break; - case 'C': - length += - add_num2 (&string[length], (tm->tm_year + 1900) / 100, - max - length, pad); - break; - case 'd': - length += - add_num2 (&string[length], tm->tm_mday, max - length, pad); - break; - case 'e': - length += - add_num2 (&string[length], tm->tm_mday, max - length, blank); - break; - case 'D': - length += - strftime (&string[length], max - length, "%m/%d/%y", tm); - break; - case 'j': - length += - add_num3 (&string[length], tm->tm_yday + 1, max - length, pad); - break; - case 'm': - length += - add_num2 (&string[length], tm->tm_mon + 1, max - length, pad); - break; - case 'U': - length += - add_num2 (&string[length], sun_week (tm), max - length, pad); - break; - case 'w': - add_char (tm->tm_wday + '0'); - break; - case 'W': - length += - add_num2 (&string[length], mon_week (tm), max - length, pad); - break; - case 'x': - length += - strftime (&string[length], max - length, "%m/%d/%y", tm); - break; - case 'y': - length += - add_num2 (&string[length], tm->tm_year % 100, - max - length, pad); - break; - case 'Y': - add_char ((tm->tm_year + 1900) / 1000 + '0'); - length += - add_num3 (&string[length], - (1900 + tm->tm_year) % 1000, max - length, zero); - break; - } - } - } - add_char (0); - return length - 1; -} diff --git a/src/bin/findutils/lib/strspn.c b/src/bin/findutils/lib/strspn.c deleted file mode 100644 index 01d8d0fc53..0000000000 --- a/src/bin/findutils/lib/strspn.c +++ /dev/null @@ -1,40 +0,0 @@ -/* strspn.c -- return numbers of chars at start of string in a class - Copyright (C) 1987, 1990 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#if defined(HAVE_STRING_H) -#include -#else -#include -#ifndef strchr -#define strchr index -#endif -#endif - -int -strspn (str, class) - char *str, *class; -{ - register char *st = str; - - while (*st && strchr (class, *st)) - ++st; - return st - str; -} diff --git a/src/bin/findutils/lib/strstr.c b/src/bin/findutils/lib/strstr.c deleted file mode 100644 index 16b748b6b0..0000000000 --- a/src/bin/findutils/lib/strstr.c +++ /dev/null @@ -1,44 +0,0 @@ -/* strstr.c -- return the offset of one string within another - Copyright (C) 1989, 1990 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -/* Written by Mike Rendell . */ - -/* Return the starting address of string S2 in S1; - return 0 if it is not found. */ - -char * -strstr (s1, s2) - char *s1; - char *s2; -{ - int i; - char *p1; - char *p2; - char *s = s1; - - for (p2 = s2, i = 0; *s; p2 = s2, i++, s++) - { - for (p1 = s; *p1 && *p2 && *p1 == *p2; p1++, p2++) - ; - if (!*p2) - break; - } - if (!*p2) - return s1 + i; - - return 0; -} diff --git a/src/bin/findutils/lib/strtol.c b/src/bin/findutils/lib/strtol.c deleted file mode 100644 index 08ef0a479b..0000000000 --- a/src/bin/findutils/lib/strtol.c +++ /dev/null @@ -1,186 +0,0 @@ -/* Copyright (C) 1991, 1992 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include -#include - -#if HAVE_LIMITS_H -#include -#endif - -#ifndef ULONG_MAX -#define ULONG_MAX ((unsigned long) ~(unsigned long) 0) -#endif - -#ifndef LONG_MAX -#define LONG_MAX (~(1 << (sizeof (long) * 8 - 1))) -#endif - -#ifndef LONG_MIN -#define LONG_MIN (-LONG_MAX - 1) -#endif - -#if STDC_HEADERS -#include -#include -#else -#define NULL 0 -extern int errno; -#endif - -#ifndef UNSIGNED -#define UNSIGNED 0 -#endif - -/* Convert NPTR to an `unsigned long int' or `long int' in base BASE. - If BASE is 0 the base is determined by the presence of a leading - zero, indicating octal or a leading "0x" or "0X", indicating hexadecimal. - If BASE is < 2 or > 36, it is reset to 10. - If ENDPTR is not NULL, a pointer to the character after the last - one converted is stored in *ENDPTR. */ -#if UNSIGNED -unsigned long int -#define strtol strtoul -#else -long int -#endif -strtol (nptr, endptr, base) - const char *nptr; - char **endptr; - int base; -{ - int negative; - register unsigned long int cutoff; - register unsigned int cutlim; - register unsigned long int i; - register const char *s; - register unsigned char c; - const char *save; - int overflow; - - if (base < 0 || base == 1 || base > 36) - base = 10; - - s = nptr; - - /* Skip white space. */ - while (isspace (*s)) - ++s; - if (*s == '\0') - goto noconv; - - /* Check for a sign. */ - if (*s == '-') - { - negative = 1; - ++s; - } - else if (*s == '+') - { - negative = 0; - ++s; - } - else - negative = 0; - - if (base == 16 && s[0] == '0' && toupper (s[1]) == 'X') - s += 2; - - /* If BASE is zero, figure it out ourselves. */ - if (base == 0) - { - if (*s == '0') - { - if (toupper (s[1]) == 'X') - { - s += 2; - base = 16; - } - else - base = 8; - } - else - base = 10; - } - - /* Save the pointer so we can check later if anything happened. */ - save = s; - - cutoff = ULONG_MAX / (unsigned long int) base; - cutlim = ULONG_MAX % (unsigned long int) base; - - overflow = 0; - i = 0; - for (c = *s; c != '\0'; c = *++s) - { - if (isdigit (c)) - c -= '0'; - else if (isalpha (c)) - c = toupper (c) - 'A' + 10; - else - break; - if (c >= base) - break; - /* Check for overflow. */ - if (i > cutoff || (i == cutoff && c > cutlim)) - overflow = 1; - else - { - i *= (unsigned long int) base; - i += c; - } - } - - /* Check if anything actually happened. */ - if (s == save) - goto noconv; - - /* Store in ENDPTR the address of one character - past the last character we converted. */ - if (endptr != NULL) - *endptr = (char *) s; - -#if !UNSIGNED - /* Check for a value that is within the range of - `unsigned long int', but outside the range of `long int'. */ - if (i > (negative ? - -(unsigned long int) LONG_MIN : (unsigned long int) LONG_MAX)) - overflow = 1; -#endif - - if (overflow) - { - errno = ERANGE; -#if UNSIGNED - return ULONG_MAX; -#else - return negative ? LONG_MIN : LONG_MAX; -#endif - } - - /* Return the result of the appropriate sign. */ - return (negative ? -i : i); - -noconv:; - /* There was no number to convert. */ - if (endptr != NULL) - *endptr = (char *) nptr; - return 0L; -} diff --git a/src/bin/findutils/lib/wait.h b/src/bin/findutils/lib/wait.h index b665288656..94ccd43415 100644 --- a/src/bin/findutils/lib/wait.h +++ b/src/bin/findutils/lib/wait.h @@ -1,20 +1,19 @@ /* wait.h -- POSIX macros for evaluating exit statuses Copyright (C) 1990 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - + along with this program. If not, see . +*/ #include /* For pid_t. */ #if HAVE_SYS_WAIT_H #include diff --git a/src/bin/findutils/lib/waitpid.c b/src/bin/findutils/lib/waitpid.c new file mode 100644 index 0000000000..cf6df48341 --- /dev/null +++ b/src/bin/findutils/lib/waitpid.c @@ -0,0 +1,81 @@ +/* Emulate waitpid on systems that just have wait. + Copyright (C) 1991, 1993, 2000, 2003, 2004, 2007 Free Software + Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#if HAVE_CONFIG_H +# include +#endif + +#include +#ifndef errno +extern int errno; +#endif + + +#if defined _MSC_VER || defined __MINGW32__ +/* Native Woe32 API. */ +#include +#else +/* Unix API. */ +#include "wait.h" +#endif + +#define WAITPID_CHILDREN 8 +static pid_t waited_pid[WAITPID_CHILDREN]; +static int waited_status[WAITPID_CHILDREN]; + +pid_t +waitpid (pid_t pid, int *stat_loc, int options) +{ + int i; + pid_t p; + + if (!options && (pid == -1 || 0 < pid)) + { + /* If we have already waited for this child, return it immediately. */ + for (i = 0; i < WAITPID_CHILDREN; i++) + { + p = waited_pid[i]; + if (p && (p == pid || pid == -1)) + { + waited_pid[i] = 0; + goto success; + } + } + + /* The child has not returned yet; wait for it, accumulating status. */ + for (i = 0; i < WAITPID_CHILDREN; i++) + if (! waited_pid[i]) + { + p = wait (&waited_status[i]); + if (p < 0) + return p; + if (p == pid || pid == -1) + goto success; + waited_pid[i] = p; + } + } + + /* We cannot emulate this wait call, e.g. because of too many children. */ + errno = EINVAL; + return -1; + +success: + if (stat_loc) + *stat_loc = waited_status[i]; + return p; +} diff --git a/src/bin/findutils/lib/xgetcwd.c b/src/bin/findutils/lib/xgetcwd.c deleted file mode 100644 index 1c1a7bd77e..0000000000 --- a/src/bin/findutils/lib/xgetcwd.c +++ /dev/null @@ -1,78 +0,0 @@ -/* xgetcwd.c -- return current directory with unlimited length - Copyright (C) 1992 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -/* Written by David MacKenzie . */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include -#include -#ifndef errno -extern int errno; -#endif -#include -#include "pathmax.h" - -#ifndef HAVE_GETCWD -char *getwd (); -#define getcwd(buf, max) getwd (buf) -#else -char *getcwd (); -#endif - -/* Amount to increase buffer size by in each try. */ -#define PATH_INCR 32 - -char *xmalloc (); -char *xrealloc (); -void free (); - -/* Return the current directory, newly allocated, arbitrarily long. - Return NULL and set errno on error. */ - -char * -xgetcwd () -{ - char *cwd; - char *ret; - unsigned path_max; - - errno = 0; - path_max = (unsigned) PATH_MAX; - path_max += 2; /* The getcwd docs say to do this. */ - - cwd = xmalloc (path_max); - - errno = 0; - while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE) - { - path_max += PATH_INCR; - cwd = xrealloc (cwd, path_max); - errno = 0; - } - - if (ret == NULL) - { - int save_errno = errno; - free (cwd); - errno = save_errno; - return NULL; - } - return cwd; -} diff --git a/src/bin/findutils/lib/xmalloc.c b/src/bin/findutils/lib/xmalloc.c deleted file mode 100644 index 9f701111bb..0000000000 --- a/src/bin/findutils/lib/xmalloc.c +++ /dev/null @@ -1,95 +0,0 @@ -/* xmalloc.c -- malloc with out of memory checking - Copyright (C) 1990, 91, 92, 93, 94 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#if __STDC__ -#define VOID void -#else -#define VOID char -#endif - -#include - -#if STDC_HEADERS -#include -#else -VOID *malloc (); -VOID *realloc (); -void free (); -#endif - -#ifndef EXIT_FAILURE -#define EXIT_FAILURE 1 -#endif - -/* Exit value when the requested amount of memory is not available. - The caller may set it to some other value. */ -int xmalloc_exit_failure = EXIT_FAILURE; - -#if __STDC__ && (HAVE_VPRINTF || HAVE_DOPRNT) -void error (int, int, const char *, ...); -#else -void error (); -#endif - -static VOID * -fixup_null_alloc (n) - size_t n; -{ - VOID *p; - - p = 0; - if (n == 0) - p = malloc ((size_t) 1); - if (p == 0) - error (xmalloc_exit_failure, 0, "memory exhausted"); - return p; -} - -/* Allocate N bytes of memory dynamically, with error checking. */ - -VOID * -xmalloc (n) - size_t n; -{ - VOID *p; - - p = malloc (n); - if (p == 0) - p = fixup_null_alloc (n); - return p; -} - -/* Change the size of an allocated block of memory P to N bytes, - with error checking. - If P is NULL, run xmalloc. */ - -VOID * -xrealloc (p, n) - VOID *p; - size_t n; -{ - if (p == 0) - return xmalloc (n); - p = realloc (p, n); - if (p == 0) - p = fixup_null_alloc (n); - return p; -} diff --git a/src/bin/findutils/lib/xstrdup.c b/src/bin/findutils/lib/xstrdup.c deleted file mode 100644 index 27cd0c6738..0000000000 --- a/src/bin/findutils/lib/xstrdup.c +++ /dev/null @@ -1,36 +0,0 @@ -/* xstrdup.c -- copy a string with out of memory checking - Copyright (C) 1990 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#if defined(STDC_HEADERS) || defined(HAVE_STRING_H) -#include -#else -#include -#endif -char *xmalloc (); - -/* Return a newly allocated copy of STRING. */ - -char * -xstrdup (string) - char *string; -{ - return strcpy (xmalloc (strlen (string) + 1), string); -} diff --git a/src/bin/findutils/locate/Jamfile b/src/bin/findutils/locate/Jamfile index d0364ce2d3..6e868e89d7 100644 --- a/src/bin/findutils/locate/Jamfile +++ b/src/bin/findutils/locate/Jamfile @@ -1,5 +1,6 @@ SubDir HAIKU_TOP src bin findutils locate ; +SubDirSysHdrs [ FDirName $(SUBDIR) $(DOTDOT) gnulib lib ] ; SubDirSysHdrs [ FDirName $(SUBDIR) $(DOTDOT) lib ] ; SubDirSysHdrs [ FDirName $(SUBDIR) $(DOTDOT) ] ; @@ -18,11 +19,11 @@ SEARCH on [ FGristFiles findutils.rdef ] = [ FDirName $(SUBDIR) $(DOTDOT) ] ; BinCommand locate : locate.c - : libfindutils.a : $(findutils_rsrc) ; + : libfindutils.a gnulibfindutils.a : $(findutils_rsrc) ; BinCommand frcode : frcode.c - : libfindutils.a : $(findutils_rsrc) ; + : libfindutils.a gnulibfindutils.a : $(findutils_rsrc) ; rule MkUpdateDb diff --git a/src/bin/findutils/locate/bigram.c b/src/bin/findutils/locate/bigram.c index ed04a81cb5..514682dc8d 100644 --- a/src/bin/findutils/locate/bigram.c +++ b/src/bin/findutils/locate/bigram.c @@ -1,19 +1,19 @@ /* bigram -- list bigrams for locate - Copyright (C) 1994 Free Software Foundation, Inc. + Copyright (C) 1994, 2000, 2003, 2004, 2005, 2007 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ /* Usage: bigram < text > bigrams Use `code' to encode a file using this output. @@ -43,7 +43,8 @@ #endif #include -char *xmalloc (); +#include +#include "closeout.h" /* The name this program was run with. */ char *program_name; @@ -51,8 +52,7 @@ char *program_name; /* Return the length of the longest common prefix of strings S1 and S2. */ static int -prefix_length (s1, s2) - char *s1, *s2; +prefix_length (char *s1, char *s2) { register char *start; @@ -61,10 +61,8 @@ prefix_length (s1, s2) return s1 - start; } -void -main (argc, argv) - int argc; - char **argv; +int +main (int argc, char **argv) { char *path; /* The current input entry. */ char *oldpath; /* The previous input entry. */ @@ -72,16 +70,17 @@ main (argc, argv) int line_len; /* Length of input line. */ program_name = argv[0]; + (void) argc; + atexit (close_stdout); - pathsize = oldpathsize = 1026; /* Increased as necessary by getstr. */ + pathsize = oldpathsize = 1026; /* Increased as necessary by getline. */ path = xmalloc (pathsize); oldpath = xmalloc (oldpathsize); - /* Set to anything not starting with a slash, to force the first - prefix count to 0. */ - strcpy (oldpath, " "); + /* Set to empty string, to force the first prefix count to 0. */ + oldpath[0] = '\0'; - while ((line_len = getstr (&path, &pathsize, stdin, '\n', 0)) > 0) + while ((line_len = getline (&path, &pathsize, stdin)) > 0) { register int count; /* The prefix length. */ register int j; /* Index into input line. */ @@ -111,5 +110,5 @@ main (argc, argv) free (path); free (oldpath); - exit (0); + return 0; } diff --git a/src/bin/findutils/locate/code.c b/src/bin/findutils/locate/code.c index 7bc3f5e634..79e46e1302 100644 --- a/src/bin/findutils/locate/code.c +++ b/src/bin/findutils/locate/code.c @@ -1,19 +1,20 @@ /* code -- bigram- and front-encode filenames for locate - Copyright (C) 1994 Free Software Foundation, Inc. + Copyright (C) 1994, 2000, 2003, 2004, 2005, 2007 Free Software + Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ /* Compress a sorted list. Works with `find' to encode a filename database to save space @@ -32,16 +33,16 @@ followed by a (partially bigram-encoded) ASCII remainder. The output lines have no terminating byte; the start of the next line is indicated by its first byte having a value <= 30. - + The encoding of the output bytes is: 0-28 likeliest differential counts + offset (14) to make nonnegative 30 escape code for out-of-range count to follow in next halfword - 128-255 bigram codes (the 128 most common, as determined by `updatedb') - 32-127 single character (printable) ASCII remainder + 128-255 bigram codes (the 128 most common, as determined by `updatedb') + 32-127 single character (printable) ASCII remainder Written by James A. Woods . - Modified by David MacKenzie . */ + Modified by David MacKenzie . */ #include #include @@ -57,9 +58,26 @@ #include #endif -#include "locatedb.h" +#if ENABLE_NLS +# include +# define _(Text) gettext (Text) +#else +# define _(Text) Text +#define textdomain(Domain) +#define bindtextdomain(Package, Directory) +#endif +#ifdef gettext_noop +# define N_(String) gettext_noop (String) +#else +/* See locate.c for explanation as to why not use (String) */ +# define N_(String) String +#endif -char *xmalloc (); +#include "locatedb.h" +#include "closeout.h" +#include "gnulib-version.h" + +char *xmalloc PARAMS((size_t)); /* The name this program was run with. */ char *program_name; @@ -68,21 +86,10 @@ char *program_name; if there are fewer. */ static char bigrams[257] = {0}; -#ifndef HAVE_PUTW -int -putw(x, fp) - int x; - FILE *fp; -{ - return (fwrite((void*)&x, sizeof(x), 1, fp) == 1 ? x : EOF); -} -#endif - /* Return the offset of PATTERN in STRING, or -1 if not found. */ static int -strindex (string, pattern) - char *string, *pattern; +strindex (char *string, char *pattern) { register char *s; @@ -102,8 +109,7 @@ strindex (string, pattern) /* Return the length of the longest common prefix of strings S1 and S2. */ static int -prefix_length (s1, s2) - char *s1, *s2; +prefix_length (char *s1, char *s2) { register char *start; @@ -112,10 +118,21 @@ prefix_length (s1, s2) return s1 - start; } -void -main (argc, argv) - int argc; - char **argv; +extern char *version_string; + +static void +usage (FILE *stream) +{ + fprintf (stream, _("\ +Usage: %s [--version | --help]\n\ +or %s most_common_bigrams < file-list > locate-database\n"), + program_name, program_name); + fputs (_("\nReport bugs to .\n"), stream); +} + + +int +main (int argc, char **argv) { char *path; /* The current input entry. */ char *oldpath; /* The previous input entry. */ @@ -127,14 +144,26 @@ main (argc, argv) int line_len; /* Length of input line. */ program_name = argv[0]; + atexit (close_stdout); bigram[2] = '\0'; if (argc != 2) { - fprintf (stderr, "Usage: %s most_common_bigrams < list > coded_list\n", - argv[0]); - exit (2); + usage(stderr); + return 2; + } + + if (0 == strcmp(argv[1], "--help")) + { + usage(stdout); + return 0; + } + else if (0 == strcmp(argv[1], "--version")) + { + printf (_("GNU findutils version %s\n"), version_string); + printf (_("Built using GNU gnulib version %s\n"), gnulib_version); + return 0; } fp = fopen (argv[1], "r"); @@ -142,16 +171,15 @@ main (argc, argv) { fprintf (stderr, "%s: ", argv[0]); perror (argv[1]); - exit (1); + return 1; } - pathsize = oldpathsize = 1026; /* Increased as necessary by getstr. */ + pathsize = oldpathsize = 1026; /* Increased as necessary by getline. */ path = xmalloc (pathsize); oldpath = xmalloc (oldpathsize); - /* Set to anything not starting with a slash, to force the first - prefix count to 0. */ - strcpy (oldpath, " "); + /* Set to empty string, to force the first prefix count to 0. */ + oldpath[0] = '\0'; oldcount = 0; /* Copy the list of most common bigrams to the output, @@ -160,7 +188,7 @@ main (argc, argv) fwrite (bigrams, 1, 256, stdout); fclose (fp); - while ((line_len = getstr (&path, &pathsize, stdin, '\n', 0)) > 0) + while ((line_len = getline (&path, &pathsize, stdin)) > 0) { char *pp; @@ -169,8 +197,7 @@ main (argc, argv) /* Squelch unprintable chars in path so as not to botch decoding. */ for (pp = path; *pp != '\0'; pp++) { - *pp &= 0177; - if (*pp < 040 || *pp == 0177) + if (!(*pp >= 040 && *pp < 0177)) *pp = '?'; } @@ -220,5 +247,5 @@ main (argc, argv) free (path); free (oldpath); - exit (0); + return 0; } diff --git a/src/bin/findutils/locate/frcode.c b/src/bin/findutils/locate/frcode.c index ac250c3332..dbfdee4d73 100644 --- a/src/bin/findutils/locate/frcode.c +++ b/src/bin/findutils/locate/frcode.c @@ -1,19 +1,19 @@ /* frcode -- front-compress a sorted list - Copyright (C) 1994 Free Software Foundation, Inc. + Copyright (C) 1994, 2003, 2006, 2007 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ /* Usage: frcode < sorted-list > compressed-list @@ -59,10 +59,12 @@ (6 = 14 - 8, and -9 = 5 - 14) Written by James A. Woods . - Modified by David MacKenzie . */ + Modified by David MacKenzie . */ #include #include +#include +#include #include #if defined(HAVE_STRING_H) || defined(STDC_HEADERS) @@ -75,9 +77,33 @@ #include #endif -#include "locatedb.h" +#if ENABLE_NLS +# include +# define _(Text) gettext (Text) +#else +# define _(Text) Text +#define textdomain(Domain) +#define bindtextdomain(Package, Directory) +#endif +#ifdef gettext_noop +# define N_(String) gettext_noop (String) +#else +/* We used to use (String) instead of just String, but apparentl;y ISO C + * doesn't allow this (at least, that's what HP said when someone reported + * this as a compiler bug). This is HP case number 1205608192. See + * also http://gcc.gnu.org/bugzilla/show_bug.cgi?id=11250 (which references + * ANSI 3.5.7p14-15). The Intel icc compiler also rejects constructs + * like: static const char buf[] = ("string"); + */ +# define N_(String) String +#endif -char *xmalloc (); + +#include "locatedb.h" +#include +#include "closeout.h" + +char *xmalloc PARAMS((size_t)); /* The name this program was run with. */ char *program_name; @@ -85,63 +111,131 @@ char *program_name; /* Write out a 16-bit int, high byte first (network byte order). */ static void -put_short (c, fp) - int c; - FILE *fp; +put_short (int c, FILE *fp) { + /* XXX: The value may be negative, but I think ISO C doesn't + * guarantee the assumptions we're making here will hold. + */ + assert(c <= SHRT_MAX); + assert(c >= SHRT_MIN); putc (c >> 8, fp); - putc (c, fp); + putc (c, fp); } /* Return the length of the longest common prefix of strings S1 and S2. */ static int -prefix_length (s1, s2) - char *s1, *s2; +prefix_length (char *s1, char *s2) { register char *start; - + int limit = INT_MAX; for (start = s1; *s1 == *s2 && *s1 != '\0'; s1++, s2++) - ; + { + /* Don't emit a prefix length that will not fit into + * our return type. + */ + if (0 == --limit) + break; + } return s1 - start; } -void -main (argc, argv) - int argc; - char **argv; +static struct option const longopts[] = +{ + {"help", no_argument, NULL, 'h'}, + {"version", no_argument, NULL, 'v'}, + {"null", no_argument, NULL, '0'}, + {NULL, no_argument, NULL, 0} +}; + +extern char *version_string; + +/* The name this program was run with. */ +char *program_name; + + +static void +usage (FILE *stream) +{ + fprintf (stream, + _("Usage: %s [-0 | --null] [--version] [--help]\n"), + program_name); + fputs (_("\nReport bugs to .\n"), stream); +} + + +int +main (int argc, char **argv) { char *path; /* The current input entry. */ char *oldpath; /* The previous input entry. */ size_t pathsize, oldpathsize; /* Amounts allocated for them. */ int count, oldcount, diffcount; /* Their prefix lengths & the difference. */ int line_len; /* Length of input line. */ + int delimiter = '\n'; + int optc; program_name = argv[0]; + atexit (close_stdout); - pathsize = oldpathsize = 1026; /* Increased as necessary by getstr. */ + pathsize = oldpathsize = 1026; /* Increased as necessary by getline. */ path = xmalloc (pathsize); oldpath = xmalloc (oldpathsize); - /* Set to anything not starting with a slash, to force the first - prefix count to 0. */ - strcpy (oldpath, " "); + oldpath[0] = 0; oldcount = 0; + + while ((optc = getopt_long (argc, argv, "hv0", longopts, (int *) 0)) != -1) + switch (optc) + { + case '0': + delimiter = 0; + break; + + case 'h': + usage (stdout); + return 0; + + case 'v': + printf (_("GNU locate version %s\n"), version_string); + return 0; + + default: + usage (stderr); + return 1; + } + + /* We expect to have no arguments. */ + if (optind != argc) + { + usage (stderr); + return 1; + } + + + fwrite (LOCATEDB_MAGIC, sizeof (LOCATEDB_MAGIC), 1, stdout); - /* FIXME temporary: change the \n to \0 when we figure out how to sort - null-terminated strings. */ - while ((line_len = getstr (&path, &pathsize, stdin, '\n', 0)) > 0) + while ((line_len = getdelim (&path, &pathsize, delimiter, stdin)) > 0) { path[line_len - 1] = '\0'; /* FIXME temporary: nuke the newline. */ count = prefix_length (oldpath, path); diffcount = count - oldcount; + if ( (diffcount > SHRT_MAX) || (diffcount < SHRT_MIN) ) + { + /* We do this to prevent overflow of the value we + * write with put_short() + */ + count = 0; + diffcount = (-oldcount); + } oldcount = count; + /* If the difference is small, it fits in one byte; otherwise, two bytes plus a marker noting that fact. */ - if (diffcount < -127 || diffcount > 127) + if (diffcount < LOCATEDB_ONEBYTE_MIN || diffcount > LOCATEDB_ONEBYTE_MAX) { putc (LOCATEDB_ESCAPE, stdout); put_short (diffcount, stdout); @@ -166,5 +260,5 @@ main (argc, argv) free (path); free (oldpath); - exit (0); + return 0; } diff --git a/src/bin/findutils/locate/locate.1 b/src/bin/findutils/locate/locate.1 index dde9cc63e4..dabb3c8bd0 100644 --- a/src/bin/findutils/locate/locate.1 +++ b/src/bin/findutils/locate/locate.1 @@ -1,9 +1,13 @@ -.TH LOCATE 1L \" -*- nroff -*- +.TH LOCATE 1 \" -*- nroff -*- .SH NAME locate \- list files in databases that match a pattern .SH SYNOPSIS .B locate -[\-d path] [\-\-database=path] [\-\-version] [\-\-help] pattern... +[\-d path | \-\-database=path] [\-e | \-E | \-\-[non\-]existing] [\-i +| \-\-ignore-case] [\-0 | \-\-null] [\-c | \-\-count] [\-w | \-\-wholename] +|\-b | \-\-basename] [\-l N | \-\-limit=N] [\-S | \-\-statistics] [\-r +| \-\-regex ] [\-P | \-H | \-\-nofollow] [\-L | \-\-follow] [\-\-version] +[\-A | \-\-all] [\-p | \-\-print] [\-\-help] pattern... .SH DESCRIPTION This manual page documents the GNU version of @@ -34,22 +38,44 @@ The file name databases contain lists of files that were on the system when the databases were last updated. The system administrator can choose the file name of the default database, the frequency with which the databases are updated, and the directories for which they contain -entries; see \fBupdatedb\fP(1L). +entries; see \fBupdatedb\fP(1). +.P +If +.BR locate 's +output is going to a terminal, unusual characters in the output are +escaped in the same way as for the \-print action of the +.B find +command. If the output is not going to a terminal, file names are +printed exactly as-is. + .SH OPTIONS .TP +.I "\-A, \-\-all" +Print only names which match all non-option arguments, not those matching +one or more non-option arguments. +.TP +.I "\-c, \-\-count" +Instead of printing the matched filenames, just print the total +number of matches we found, unless \-\-\fIprint\fP (\-p) is also present. +.TP .I "\-d \fIpath\fP, \-\-database=\fIpath\fP" Instead of searching the default file name database, search the file name databases in \fIpath\fP, which is a colon-separated list of database file names. You can also use the environment variable .B LOCATE_PATH to set the list of database files to search. -The option overrides the environment variable if both are used. -.P +The option overrides the environment variable if both are used. Empty +elements in the path are taken to be synonyms for the file name of the +default database. +A database can be supplied on stdin, using `\-' as an element +of \fIpath\fP. If more than one element of \fIpath\fP is `\-', +later instances are ignored (and a warning message is printed). +.IP The file name database format changed starting with GNU .B find and .B locate -version 4.0 to allow machines with diffent byte orderings to share +version 4.0 to allow machines with different byte orderings to share the databases. This version of .B locate can automatically recognize and read databases produced for older @@ -59,6 +85,89 @@ or Unix versions of .B locate or .BR find . +Support for the old locate database format will be discontinued in a +future release. +.TP +.I "\-e, \-\-existing" +Only print out such names that currently exist (instead of such names +that existed when the database was created). +Note that this may slow down the program a lot, if there are many matches +in the database. If you are using this option within a program, +please note that it is possible for the file to be deleted after +.B locate +has checked that it exists, but before you use it. +.TP +.I "\-E, \-\-non\-existing" +Only print out such names that currently do not exist (instead of such names +that existed when the database was created). +Note that this may slow down the program a lot, if there are many matches +in the database. +.TP +.I "\-L, \-\-follow" +If testing for the existence of files (with the \-e or \-E options), +consider broken symbolic links to be non-existing. This is the default. +.TP +.I "\-P, \-H, \-\-nofollow" +If testing for the existence of files (with the \-e or \-E options), treat +broken symbolic links as if they were existing files. The \-H +form of this option is provided purely for similarity with +.BR find ; +the use of \-P is recommended over \-H. +.TP +.I "\-i, \-\-ignore-case" +Ignore case distinctions in both the pattern and the file names. +.TP +.I "\-l N, \-\-limit=N" +Limit the number of matches to N. If a limit is set via this option, +the number of results printed for the \-c option will never be larger +than this number. +.TP +.I "\-m, \-\-mmap" +Accepted but does nothing, for compatibility with BSD +.BR locate . +.TP +.I "\-0, \-\-null" +Use ASCII NUL as a separator, instead of newline. +.TP +.I "\-p, \-\-print" +Print search results when they normally would not, because of the presence +of \-\-statistics (\-S) or \-\-count (\-c). +.TP +.I "\-w, \-\-wholename" +Match against the whole name of the file as listed in the database. +This is the default. +.TP +.I "\-b, \-\-basename" +Results are considered to match if the pattern specified matches the +final component of the name of a file as listed in the database. +This final component is usually referred to as the `base name'. +.TP +.I "\-r, \-\-regex " +The pattern specified on the command line is understood to be a +regular expression, as opposed to a glob pattern. The Regular +expressions work in the same was as in +.B emacs +and +.BR find , +except for the fact that "." will match a newline. +Filenames whose full paths match the specified regular expression are +printed (or, in the case of the \-c option, counted). If you wish to +anchor your regular expression at the ends of the full path name, then +as is usual with regular expressions, you should use the characters ^ +and $ to signify this. +.TP +.I "\-s, \-\-stdio" +Accepted but does nothing, for compatibility with BSD +.BR locate . +.TP +.I "\-S, \-\-statistics" +Print various statistics about each locate database and then exit +without performing a search, unless non-option arguments are given. +For compatibility with BSD, \-S is accepted as a synonym +for \-\-statistics. However, the ouptut of +.B locate \-S +is different for the GNU and BSD implementations of +.BR locate . .TP .I "\-\-help" Print a summary of the options to @@ -72,7 +181,37 @@ and exit. .SH ENVIRONMENT .TP .B LOCATE_PATH -Colon-separated list of databases to search. +Colon-separated list of databases to search. If the value has a +leading or trailing colon, or has two colons in a row, you may get +results that vary between different versions of +.BR locate . + .SH "SEE ALSO" -\fBfind\fP(1L), \fBlocatedb\fP(5L), \fBupdatedb\fP(1L), \fBxargs\fP(1L) +\fBfind\fP(1), \fBlocatedb\fP(5), \fBupdatedb\fP(1), \fBxargs\fP(1), +\fBglob\fP(3), \fBFinding Files\fP (on-line in Info, or printed) +.SH "BUGS" +.P +All versions of GNU locate prior to 4.2.31 fail to correctly handle +long (roughly, over 1024 bytes) filenames in old-format databases. +This can lead to a heap buffer overrun and it a potential security +issue. Verions 4.3.0 to 4.3.6 are also affected by the bug. +Databases in the default LOCATE02 format are correctly handled. +.P +The locate database correctly handles filenames containing newlines, +but only if the system's sort command has a working +.I \-z +option. If you suspect that +.B locate +may need to return filenames containing newlines, consider using its +.I \-\-null +option. +.P +The best way to report a bug is to use the form at +http://savannah.gnu.org/bugs/?group=findutils. +The reason for this is that you will then be able to track progress in +fixing the problem. Other comments about \fBlocate\fP(1) and about +the findutils package in general can be sent to the +.I bug-findutils +mailing list. To join the list, send email to +.IR bug-findutils-request@gnu.org . diff --git a/src/bin/findutils/locate/locate.c b/src/bin/findutils/locate/locate.c index 1721b33842..302b3e7ecf 100644 --- a/src/bin/findutils/locate/locate.c +++ b/src/bin/findutils/locate/locate.c @@ -1,19 +1,20 @@ /* locate -- search databases for filenames that match patterns - Copyright (C) 1994 Free Software Foundation, Inc. + Copyright (C) 1994, 1996, 1998, 1999, 2000, 2003, + 2004, 2005, 2007 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ /* Usage: locate [options] pattern... @@ -27,33 +28,52 @@ 0-28 likeliest differential counts + offset (14) to make nonnegative 30 escape code for out-of-range count to follow in next halfword - 128-255 bigram codes (the 128 most common, as determined by `updatedb') - 32-127 single character (printable) ASCII remainder + 128-255 bigram codes (the 128 most common, as determined by `updatedb') + 32-127 single character (printable) ASCII remainder - Uses a novel two-tiered string search technique: + Earlier versions of GNU locate used to use a novel two-tiered + string search technique, which was described in Usenix ;login:, Vol + 8, No 1, February/March, 1983, p. 8. - First, match a metacharacter-free subpattern and a partial pathname - BACKWARDS to avoid full expansion of the pathname list. - The time savings is 40-50% over forward matching, which cannot efficiently - handle overlapped search patterns and compressed path remainders. + However, latterly code changes to provide additional functionality + became dificult to make with the existing reading scheme, and so + we no longer perform the matching as efficiently as we used to (that is, + we no longer use the same algorithm). - Then, match the actual shell glob-style regular expression (if in this form) - against the candidate pathnames using the slower shell filename - matching routines. + The old algorithm was: + + First, match a metacharacter-free subpattern and a partial + pathname BACKWARDS to avoid full expansion of the pathname list. + The time savings is 40-50% over forward matching, which cannot + efficiently handle overlapped search patterns and compressed + path remainders. + + Then, match the actual shell glob pattern (if in this form) + against the candidate pathnames using the slower shell filename + matching routines. - Described more fully in Usenix ;login:, Vol 8, No 1, - February/March, 1983, p. 8. Written by James A. Woods . - Modified by David MacKenzie . */ + Modified by David MacKenzie . + Additional work by James Youngman and Bas van Gompel. +*/ #include #include +#include #include #include #include #include #include +#include + +/* The presence of unistd.h is assumed by gnulib these days, so we + * might as well assume it too. + */ +/* We need for isatty(). */ +#include + #define NDEBUG #include @@ -67,347 +87,1310 @@ #ifdef STDC_HEADERS #include -#else -char *getenv (); #endif -#ifdef STDC_HEADERS +#ifdef HAVE_ERRNO_H #include -#include #else extern int errno; #endif -#include "locatedb.h" +#ifdef HAVE_LOCALE_H +#include +#endif -typedef enum {false, true} boolean; +#if ENABLE_NLS +# include +# define _(Text) gettext (Text) +#else +# define _(Text) Text +#define textdomain(Domain) +#define bindtextdomain(Package, Directory) +#endif +#ifdef gettext_noop +# define N_(String) gettext_noop (String) +#else +/* We used to use (String) instead of just String, but apparentl;y ISO C + * doesn't allow this (at least, that's what HP said when someone reported + * this as a compiler bug). This is HP case number 1205608192. See + * also http://gcc.gnu.org/bugzilla/show_bug.cgi?id=11250 (which references + * ANSI 3.5.7p14-15). The Intel icc compiler also rejects constructs + * like: static const char buf[] = ("string"); + */ +# define N_(String) String +#endif + +#include "locatedb.h" +#include "xalloc.h" +#include "error.h" +#include "human.h" +#include "dirname.h" +#include "closeout.h" +#include "nextelem.h" +#include "regex.h" +#include "quote.h" +#include "quotearg.h" +#include "printquoted.h" +#include "regextype.h" +#include "gnulib-version.h" + +/* Note that this evaluates C many times. */ +#ifdef _LIBC +# define TOUPPER(Ch) toupper (Ch) +# define TOLOWER(Ch) tolower (Ch) +#else +# define TOUPPER(Ch) (islower (Ch) ? toupper (Ch) : (Ch)) +# define TOLOWER(Ch) (isupper (Ch) ? tolower (Ch) : (Ch)) +#endif + +/* typedef enum {false, true} boolean; */ /* Warn if a database is older than this. 8 days allows for a weekly update that takes up to a day to perform. */ -#define WARN_SECONDS (60 * 60 * 24 * 8) +#define WARN_NUMBER_UNITS (8) +/* Printable name of units used in WARN_SECONDS */ +static const char warn_name_units[] = N_("days"); +#define SECONDS_PER_UNIT (60 * 60 * 24) -/* Printable version of WARN_SECONDS. */ -#define WARN_MESSAGE "8 days" +#define WARN_SECONDS ((SECONDS_PER_UNIT) * (WARN_NUMBER_UNITS)) -char *next_element (); -char *xmalloc (); -char *xrealloc (); -void error (); +enum visit_result + { + VISIT_CONTINUE = 1, /* please call the next visitor */ + VISIT_ACCEPTED = 2, /* accepted, call no futher callbacks for this file */ + VISIT_REJECTED = 4, /* rejected, process next file. */ + VISIT_ABORT = 8 /* rejected, process no more files. */ + }; -#ifndef HAVE_GETW -int -getw(fp) - FILE *fp; -{ - int x; - - return (fread((void*)&x, sizeof(x), 1, fp) == 1 ? x : EOF); -} -#endif +enum ExistenceCheckType + { + ACCEPT_EITHER, /* Corresponds to lack of -E/-e option */ + ACCEPT_EXISTING, /* Corresponds to option -e */ + ACCEPT_NON_EXISTING /* Corresponds to option -E */ + }; + +/* Check for existence of files before printing them out? */ +enum ExistenceCheckType check_existence = ACCEPT_EITHER; + +static int follow_symlinks = 1; + +/* What to separate the results with. */ +static int separator = '\n'; + +static struct quoting_options * quote_opts = NULL; +static bool stdout_is_a_tty; +static bool print_quoted_filename; /* Read in a 16-bit int, high byte first (network byte order). */ -static int -get_short (fp) - FILE *fp; +static short +get_short (FILE *fp) { + register short x; - x = fgetc (fp); - return (x << 8) | (fgetc (fp) & 0xff); + x = (signed char) fgetc (fp) << 8; + x |= (fgetc (fp) & 0xff); + return x; } -/* Return a pointer to the last character in a static copy of the last - glob-free subpattern in NAME, - with '\0' prepended for a fast backwards pre-match. */ +const char * const metacharacters = "*?[]\\"; -static char * -last_literal_end (name) - char *name; +/* Return nonzero if S contains any shell glob characters. + */ +static int +contains_metacharacter(const char *s) { - static char *globfree = NULL; /* A copy of the subpattern in NAME. */ - static size_t gfalloc = 0; /* Bytes allocated for `globfree'. */ - register char *subp; /* Return value. */ - register char *p; /* Search location in NAME. */ + if (NULL == strpbrk(s, metacharacters)) + return 0; + else + return 1; +} - /* Find the end of the subpattern. - Skip trailing metacharacters and [] ranges. */ - for (p = name + strlen (name) - 1; p >= name && strchr ("*?]", *p) != NULL; - p--) +/* locate_read_str() + * + * Read bytes from FP into the buffer at offset OFFSET in (*BUF), + * until we reach DELIMITER or end-of-file. We reallocate the buffer + * as necessary, altering (*BUF) and (*SIZ) as appropriate. No assumption + * is made regarding the content of the data (i.e. the implementation is + * 8-bit clean, the only delimiter is DELIMITER). + * + * Written Fri May 23 18:41:16 2003 by James Youngman, because getstr() + * has been removed from gnulib. + * + * We call the function locate_read_str() to avoid a name clash with the curses + * function getstr(). + */ +static int +locate_read_str(char **buf, size_t *siz, FILE *fp, int delimiter, int offs) +{ + char * p = NULL; + size_t sz = 0; + int needed, nread; + + nread = getdelim(&p, &sz, delimiter, fp); + if (nread >= 0) { - if (*p == ']') - while (p >= name && *p != '[') - p--; + assert(p != NULL); + + needed = offs + nread + 1; + if (needed > (*siz)) + { + char *pnew = realloc(*buf, needed); + if (NULL == pnew) + { + return -1; /* FAIL */ + } + else + { + *siz = needed; + *buf = pnew; + } + } + memcpy((*buf)+offs, p, nread); + free(p); } - if (p < name) - p = name; + return nread; +} - if (p - name + 3 > gfalloc) + +static void +lc_strcpy(char *dest, const char *src) +{ + while (*src) { - gfalloc = p - name + 3 + 64; /* Room to grow. */ - globfree = xrealloc (globfree, gfalloc); + *dest++ = TOLOWER(*src); + ++src; } - subp = globfree; - *subp++ = '\0'; + *dest = 0; +} - /* If the pattern has only metacharacters, make every path match the - subpattern, so it gets checked the slow way. */ - if (p == name && strchr ("?*[]", *p) != NULL) - *subp++ = '/'; +struct locate_limits +{ + uintmax_t limit; + uintmax_t items_accepted; +}; +static struct locate_limits limits; + + +struct locate_stats +{ + uintmax_t compressed_bytes; + uintmax_t total_filename_count; + uintmax_t total_filename_length; + uintmax_t whitespace_count; + uintmax_t newline_count; + uintmax_t highbit_filename_count; +}; +static struct locate_stats statistics; + + +struct stringbuf +{ + char *buffer; + size_t buffersize; + size_t *preqlen; +}; +static struct stringbuf casebuf; + + +struct casefolder +{ + const char *pattern; + struct stringbuf *pbuf; +}; + +struct regular_expression +{ + struct re_pattern_buffer regex; /* for --regex */ +}; + + +struct process_data +{ + int c; /* An input byte. */ + int count; /* The length of the prefix shared with the previous database entry. */ + int len; + char *original_filename; /* The current input database entry. */ + size_t pathsize; /* Amount allocated for it. */ + char *munged_filename; /* path or basename(path) */ + FILE *fp; /* The pathname database. */ + char *dbfile; /* Its name, or "" */ + /* for the old database format, + the first and second characters of the most common bigrams. */ + char bigram1[128]; + char bigram2[128]; +}; + + +typedef int (*visitfunc)(struct process_data *procdata, + void *context); + +struct visitor +{ + visitfunc inspector; + void * context; + struct visitor *next; +}; + + +static struct visitor *inspectors = NULL; +static struct visitor *lastinspector = NULL; +static struct visitor *past_pat_inspector = NULL; + +/* 0 or 1 pattern(s) */ +static int +process_simple(struct process_data *procdata) +{ + int result = VISIT_CONTINUE; + const struct visitor *p = inspectors; + + while ( ((VISIT_CONTINUE | VISIT_ACCEPTED) & result) && (NULL != p) ) + { + result = (p->inspector)(procdata, p->context); + p = p->next; + } + + return result; +} + +/* Accept if any pattern matches. */ +static int +process_or (struct process_data *procdata) +{ + int result = VISIT_CONTINUE; + const struct visitor *p = inspectors; + + while ( ((VISIT_CONTINUE | VISIT_REJECTED) & result) && (past_pat_inspector != p) ) + { + result = (p->inspector)(procdata, p->context); + p = p->next; + } + + if (result == VISIT_CONTINUE) + result = VISIT_REJECTED; + if (result & (VISIT_ABORT | VISIT_REJECTED)) + return result; + + p = past_pat_inspector; + result = VISIT_CONTINUE; + + while ( (VISIT_CONTINUE == result) && (NULL != p) ) + { + result = (p->inspector)(procdata, p->context); + p = p->next; + } + + if (VISIT_CONTINUE == result) + return VISIT_ACCEPTED; + else + return result; +} + +/* Accept if all pattern match. */ +static int +process_and (struct process_data *procdata) +{ + int result = VISIT_CONTINUE; + const struct visitor *p = inspectors; + + while ( ((VISIT_CONTINUE | VISIT_ACCEPTED) & result) && (past_pat_inspector != p) ) + { + result = (p->inspector)(procdata, p->context); + p = p->next; + } + + if (result == VISIT_CONTINUE) + result = VISIT_REJECTED; + if (result & (VISIT_ABORT | VISIT_REJECTED)) + return result; + + p = past_pat_inspector; + result = VISIT_CONTINUE; + + while ( (VISIT_CONTINUE == result) && (NULL != p) ) + { + result = (p->inspector)(procdata, p->context); + p = p->next; + } + + if (VISIT_CONTINUE == result) + return VISIT_ACCEPTED; + else + return result; +} + +typedef int (*processfunc)(struct process_data *procdata); + +static processfunc mainprocessor = NULL; + +static void +add_visitor(visitfunc fn, void *context) +{ + struct visitor *p = xmalloc(sizeof(struct visitor)); + p->inspector = fn; + p->context = context; + p->next = NULL; + + if (NULL == lastinspector) + { + lastinspector = inspectors = p; + } else { - char *endmark; - /* Find the start of the metacharacter-free subpattern. */ - for (endmark = p; p >= name && strchr ("]*?", *p) == NULL; p--) - ; - /* Copy the subpattern into globfree. */ - for (++p; p <= endmark; ) - *subp++ = *p++; + lastinspector->next = p; + lastinspector = p; } - *subp-- = '\0'; /* Null terminate, though it's not needed. */ - - return subp; } -/* Print the entries in DBFILE that match shell globbing pattern PATHPART. - Return the number of entries printed. */ + static int -locate (pathpart, dbfile) - char *pathpart, *dbfile; +visit_justprint_quoted(struct process_data *procdata, void *context) { - /* The pathname database. */ - FILE *fp; - /* An input byte. */ - int c; - /* Number of bytes read from an entry. */ + (void) context; + print_quoted (stdout, quote_opts, stdout_is_a_tty, + "%s", + procdata->original_filename); + putchar(separator); + return VISIT_CONTINUE; +} + +static int +visit_justprint_unquoted(struct process_data *procdata, void *context) +{ + (void) context; + fputs(procdata->original_filename, stdout); + putchar(separator); + return VISIT_CONTINUE; +} + +static void +toolong (struct process_data *procdata) +{ + error (1, 0, + _("locate database %s contains a " + "filename longer than locate can handle"), + procdata->dbfile); +} + +static void +extend (struct process_data *procdata, size_t siz1, size_t siz2) +{ + /* Figure out if the addition operation is safe before performing it. */ + if (SIZE_MAX - siz1 < siz2) + { + toolong (procdata); + } + else if (procdata->pathsize < (siz1+siz2)) + { + procdata->pathsize = siz1+siz2; + procdata->original_filename = x2nrealloc (procdata->original_filename, + &procdata->pathsize, + 1); + } +} + +static int +visit_old_format(struct process_data *procdata, void *context) +{ + register size_t i; + (void) context; + + if (EOF == procdata->c) + return VISIT_ABORT; + + /* Get the offset in the path where this path info starts. */ + if (procdata->c == LOCATEDB_OLD_ESCAPE) + procdata->count += getw (procdata->fp) - LOCATEDB_OLD_OFFSET; + else + procdata->count += procdata->c - LOCATEDB_OLD_OFFSET; + assert(procdata->count > 0); + + /* Overlay the old path with the remainder of the new. Read + * more data until we get to the next filename. + */ + for (i=procdata->count; + (procdata->c = getc (procdata->fp)) > LOCATEDB_OLD_ESCAPE;) + { + if (EOF == procdata->c) + break; + + if (procdata->c < 0200) + { + /* An ordinary character. */ + extend (procdata, i, 1u); + procdata->original_filename[i++] = procdata->c; + } + else + { + /* Bigram markers have the high bit set. */ + extend (procdata, i, 2u); + procdata->c &= 0177; + procdata->original_filename[i++] = procdata->bigram1[procdata->c]; + procdata->original_filename[i++] = procdata->bigram2[procdata->c]; + } + } + + /* Consider the case where we executed the loop body zero times; we + * still need space for the terminating null byte. + */ + extend (procdata, i, 1u); + procdata->original_filename[i] = 0; + + procdata->munged_filename = procdata->original_filename; + + return VISIT_CONTINUE; +} + + +static int +visit_locate02_format(struct process_data *procdata, void *context) +{ + register char *s; int nread; + (void) context; - /* true if PATHPART contains globbing metacharacters. */ - boolean globflag; - /* The end of the last glob-free subpattern in PATHPART. */ - char *patend; + if (procdata->c == LOCATEDB_ESCAPE) + procdata->count += (short)get_short (procdata->fp); + else if (procdata->c > 127) + procdata->count += procdata->c - 256; + else + procdata->count += procdata->c; - /* The current input database entry. */ - char *path; - /* Amount allocated for it. */ - size_t pathsize; + if (procdata->count > procdata->len || procdata->count < 0) + { + /* This should not happen generally , but since we're + * reading in data which is outside our control, we + * cannot prevent it. + */ + error(1, 0, _("locate database `%s' is corrupt or invalid"), procdata->dbfile); + } + + /* Overlay the old path with the remainder of the new. */ + nread = locate_read_str (&procdata->original_filename, &procdata->pathsize, + procdata->fp, 0, procdata->count); + if (nread < 0) + return VISIT_ABORT; + procdata->c = getc (procdata->fp); + procdata->len = procdata->count + nread; + s = procdata->original_filename + procdata->len - 1; /* Move to the last char in path. */ + assert (s[0] != '\0'); + assert (s[1] == '\0'); /* Our terminator. */ + assert (s[2] == '\0'); /* Added by locate_read_str. */ - /* The length of the prefix shared with the previous database entry. */ - int count = 0; - /* Where in `path' to stop the backward search for the last character - in the subpattern. Set according to `count'. */ - char *cutoff; + procdata->munged_filename = procdata->original_filename; + + return VISIT_CONTINUE; +} - /* true if we found a fast match (of patend) on the previous path. */ - boolean prev_fast_match = false; - /* The return value. */ - int printed = 0; +static int +visit_basename(struct process_data *procdata, void *context) +{ + (void) context; + procdata->munged_filename = last_component (procdata->original_filename); - /* true if reading a bigram-encoded database. */ - boolean old_format = false; - /* For the old database format, - the first and second characters of the most common bigrams. */ - char bigram1[128], bigram2[128]; + return VISIT_CONTINUE; +} + +static int +visit_casefold(struct process_data *procdata, void *context) +{ + struct stringbuf *b = context; + + if (*b->preqlen+1 > b->buffersize) + { + b->buffer = xrealloc(b->buffer, *b->preqlen+1); /* XXX: consider using extendbuf(). */ + b->buffersize = *b->preqlen+1; + } + lc_strcpy(b->buffer, procdata->munged_filename); + + return VISIT_CONTINUE; +} + +/* visit_existing_follow implements -L -e */ +static int +visit_existing_follow(struct process_data *procdata, void *context) +{ + struct stat st; + (void) context; + + /* munged_filename has been converted in some way (to lower case, + * or is just the base name of the file), and original_filename has not. + * Hence only original_filename is still actually the name of the file + * whose existence we would need to check. + */ + if (stat(procdata->original_filename, &st) != 0) + { + return VISIT_REJECTED; + } + else + { + return VISIT_CONTINUE; + } +} + +/* visit_non_existing_follow implements -L -E */ +static int +visit_non_existing_follow(struct process_data *procdata, void *context) +{ + struct stat st; + (void) context; + + /* munged_filename has been converted in some way (to lower case, + * or is just the base name of the file), and original_filename has not. + * Hence only original_filename is still actually the name of the file + * whose existence we would need to check. + */ + if (stat(procdata->original_filename, &st) == 0) + { + return VISIT_REJECTED; + } + else + { + return VISIT_CONTINUE; + } +} + +/* visit_existing_nofollow implements -P -e */ +static int +visit_existing_nofollow(struct process_data *procdata, void *context) +{ + struct stat st; + (void) context; + + /* munged_filename has been converted in some way (to lower case, + * or is just the base name of the file), and original_filename has not. + * Hence only original_filename is still actually the name of the file + * whose existence we would need to check. + */ + if (lstat(procdata->original_filename, &st) != 0) + { + return VISIT_REJECTED; + } + else + { + return VISIT_CONTINUE; + } +} + +/* visit_non_existing_nofollow implements -P -E */ +static int +visit_non_existing_nofollow(struct process_data *procdata, void *context) +{ + struct stat st; + (void) context; + + /* munged_filename has been converted in some way (to lower case, + * or is just the base name of the file), and original_filename has not. + * Hence only original_filename is still actually the name of the file + * whose existence we would need to check. + */ + if (lstat(procdata->original_filename, &st) == 0) + { + return VISIT_REJECTED; + } + else + { + return VISIT_CONTINUE; + } +} + +static int +visit_substring_match_nocasefold(struct process_data *procdata, void *context) +{ + const char *pattern = context; + + if (NULL != strstr(procdata->munged_filename, pattern)) + return VISIT_ACCEPTED; + else + return VISIT_REJECTED; +} + +static int +visit_substring_match_casefold(struct process_data *procdata, void *context) +{ + const struct casefolder * p = context; + const struct stringbuf * b = p->pbuf; + (void) procdata; + + if (NULL != strstr(b->buffer, p->pattern)) + return VISIT_ACCEPTED; + else + return VISIT_REJECTED; +} + + +static int +visit_globmatch_nofold(struct process_data *procdata, void *context) +{ + const char *glob = context; + if (fnmatch(glob, procdata->munged_filename, 0) != 0) + return VISIT_REJECTED; + else + return VISIT_ACCEPTED; +} + + +static int +visit_globmatch_casefold(struct process_data *procdata, void *context) +{ + const char *glob = context; + if (fnmatch(glob, procdata->munged_filename, FNM_CASEFOLD) != 0) + return VISIT_REJECTED; + else + return VISIT_ACCEPTED; +} + + +static int +visit_regex(struct process_data *procdata, void *context) +{ + struct regular_expression *p = context; + const size_t len = strlen(procdata->munged_filename); + + int rv = re_search (&p->regex, procdata->munged_filename, + len, 0, len, + (struct re_registers *) NULL); + if (rv < 0) + { + return VISIT_REJECTED; /* no match (-1), or internal error (-2) */ + } + else + { + return VISIT_ACCEPTED; /* match */ + } +} + + +static int +visit_stats(struct process_data *procdata, void *context) +{ + struct locate_stats *p = context; + size_t len = strlen(procdata->original_filename); + const char *s; + int highbit, whitespace, newline; + + ++(p->total_filename_count); + p->total_filename_length += len; + + highbit = whitespace = newline = 0; + for (s=procdata->original_filename; *s; ++s) + { + if ( (int)(*s) & 128 ) + highbit = 1; + if ('\n' == *s) + { + newline = whitespace = 1; + } + else if (isspace((unsigned char)*s)) + { + whitespace = 1; + } + } + + if (highbit) + ++(p->highbit_filename_count); + if (whitespace) + ++(p->whitespace_count); + if (newline) + ++(p->newline_count); + + return VISIT_CONTINUE; +} + + +static int +visit_limit(struct process_data *procdata, void *context) +{ + struct locate_limits *p = context; + + (void) procdata; + + if (++p->items_accepted >= p->limit) + return VISIT_ABORT; + else + return VISIT_CONTINUE; +} + +static int +visit_count(struct process_data *procdata, void *context) +{ + struct locate_limits *p = context; + + (void) procdata; + + ++p->items_accepted; + return VISIT_CONTINUE; +} + +/* Emit the statistics. + */ +static void +print_stats(int argc, size_t database_file_size) +{ + char hbuf[LONGEST_HUMAN_READABLE + 1]; + + printf(_("Locate database size: %s bytes\n"), + human_readable ((uintmax_t) database_file_size, + hbuf, human_ceiling, 1, 1)); + + printf(_("Filenames: %s "), + human_readable (statistics.total_filename_count, + hbuf, human_ceiling, 1, 1)); + printf(_("with a cumulative length of %s bytes"), + human_readable (statistics.total_filename_length, + hbuf, human_ceiling, 1, 1)); + + printf(_("\n\tof which %s contain whitespace, "), + human_readable (statistics.whitespace_count, + hbuf, human_ceiling, 1, 1)); + printf(_("\n\t%s contain newline characters, "), + human_readable (statistics.newline_count, + hbuf, human_ceiling, 1, 1)); + printf(_("\n\tand %s contain characters with the high bit set.\n"), + human_readable (statistics.highbit_filename_count, + hbuf, human_ceiling, 1, 1)); + + if (!argc) + printf(_("Compression ratio %4.2f%%\n"), + 100.0 * ((double)statistics.total_filename_length + - (double) database_file_size) + / (double) statistics.total_filename_length); + printf("\n"); +} + + +/* Print or count the entries in DBFILE that match shell globbing patterns in + ARGV. Return the number of entries matched. */ + +static unsigned long +locate (int argc, + char **argv, + char *dbfile, + int ignore_case, + int enable_print, + int basename_only, + int use_limit, + struct locate_limits *plimit, + int stats, + int op_and, + int regex, + int regex_options) +{ + char *pathpart; /* A pattern to consider. */ + int argn; /* Index to current pattern in argv. */ + int need_fold; /* Set when folding and any pattern is non-glob. */ + int nread; /* number of bytes read from an entry. */ + struct process_data procdata; /* Storage for data shared with visitors. */ + + int old_format = 0; /* true if reading a bigram-encoded database. */ + static bool did_stdin = false; /* Set to prevent rereading stdin. */ + struct visitor* pvis; /* temp for determining past_pat_inspector. */ + /* To check the age of the database. */ struct stat st; time_t now; - if (stat (dbfile, &st) || (fp = fopen (dbfile, "r")) == NULL) + + if (ignore_case) + regex_options |= RE_ICASE; + + procdata.len = procdata.count = 0; + if (!strcmp (dbfile, "-")) { - error (0, errno, "%s", dbfile); - return 0; + if (did_stdin) + { + error (0, 0, _("warning: the locate database can only be read from stdin once.")); + return 0; + } + + + procdata.dbfile = ""; + procdata.fp = stdin; + did_stdin = true; } - time(&now); - if (now - st.st_mtime > WARN_SECONDS) + else { - error (0, 0, "warning: database `%s' is more than %s old", - dbfile, WARN_MESSAGE); + if (stat (dbfile, &st) || (procdata.fp = fopen (dbfile, "r")) == NULL) + { + error (0, errno, "%s", dbfile); + return 0; + } + time(&now); + if (now - st.st_mtime > WARN_SECONDS) + { + /* For example: + warning: database `fred' is more than 8 days old */ + error (0, 0, _("warning: database `%s' is more than %d %s old"), + dbfile, WARN_NUMBER_UNITS, _(warn_name_units)); + } + procdata.dbfile = dbfile; } - pathsize = 1026; /* Increased as necessary by getstr. */ - path = xmalloc (pathsize); + procdata.pathsize = 1026; /* Increased as necessary by locate_read_str. */ + procdata.original_filename = xmalloc (procdata.pathsize); - nread = fread (path, 1, sizeof (LOCATEDB_MAGIC), fp); + nread = fread (procdata.original_filename, 1, sizeof (LOCATEDB_MAGIC), + procdata.fp); if (nread != sizeof (LOCATEDB_MAGIC) - || memcmp (path, LOCATEDB_MAGIC, sizeof (LOCATEDB_MAGIC))) + || memcmp (procdata.original_filename, LOCATEDB_MAGIC, + sizeof (LOCATEDB_MAGIC))) { int i; /* Read the list of the most common bigrams in the database. */ - fseek (fp, 0, 0); + nread = fread (procdata.original_filename + sizeof (LOCATEDB_MAGIC), 1, + 256 - sizeof (LOCATEDB_MAGIC), procdata.fp); for (i = 0; i < 128; i++) { - bigram1[i] = getc (fp); - bigram2[i] = getc (fp); + procdata.bigram1[i] = procdata.original_filename[i << 1]; + procdata.bigram2[i] = procdata.original_filename[(i << 1) + 1]; } - old_format = true; + old_format = 1; } - globflag = strchr (pathpart, '*') || strchr (pathpart, '?') - || strchr (pathpart, '['); + /* Set up the inspection regime */ + inspectors = NULL; + lastinspector = NULL; + past_pat_inspector = NULL; - patend = last_literal_end (pathpart); + if (old_format) + add_visitor(visit_old_format, NULL); + else + add_visitor(visit_locate02_format, NULL); - c = getc (fp); - while (c != EOF) + if (basename_only) + add_visitor(visit_basename, NULL); + + /* See if we need fold. */ + if (ignore_case && !regex) + for ( argn = 0; argn < argc; argn++ ) + { + pathpart = argv[argn]; + if (!contains_metacharacter(pathpart)) + { + need_fold = 1; + break; + } + } + + if (need_fold) { - register char *s; /* Scan the path we read in. */ - - if (old_format) + add_visitor(visit_casefold, &casebuf); + casebuf.preqlen = &procdata.pathsize; + } + + /* Add an inspector for each pattern we're looking for. */ + for ( argn = 0; argn < argc; argn++ ) + { + pathpart = argv[argn]; + if (regex) { - /* Get the offset in the path where this path info starts. */ - if (c == LOCATEDB_OLD_ESCAPE) - count += getw (fp) - LOCATEDB_OLD_OFFSET; - else - count += c - LOCATEDB_OLD_OFFSET; + struct regular_expression *p = xmalloc(sizeof(*p)); + const char *error_message = NULL; + + memset (&p->regex, 0, sizeof (p->regex)); + + re_set_syntax(regex_options); + p->regex.allocated = 100; + p->regex.buffer = (unsigned char *) xmalloc (p->regex.allocated); + p->regex.fastmap = NULL; + p->regex.syntax = regex_options; + p->regex.translate = NULL; - /* Overlay the old path with the remainder of the new. */ - for (s = path + count; (c = getc (fp)) > LOCATEDB_OLD_ESCAPE;) - if (c < 0200) - *s++ = c; /* An ordinary character. */ - else - { - /* Bigram markers have the high bit set. */ - c &= 0177; - *s++ = bigram1[c]; - *s++ = bigram2[c]; - } - *s-- = '\0'; + error_message = re_compile_pattern (pathpart, strlen (pathpart), + &p->regex); + if (error_message) + { + error (1, 0, "%s", error_message); + } + else + { + add_visitor(visit_regex, p); + } + } + else if (contains_metacharacter(pathpart)) + { + if (ignore_case) + add_visitor(visit_globmatch_casefold, pathpart); + else + add_visitor(visit_globmatch_nofold, pathpart); } else { - if (c == LOCATEDB_ESCAPE) - count += get_short (fp); - else if (c > 127) - count += c - 256; + /* No glob characters used. Hence we match on + * _any part_ of the filename, not just the + * basename. This seems odd to me, but it is the + * traditional behaviour. + * James Youngman + */ + if (ignore_case) + { + struct casefolder * cf = xmalloc(sizeof(*cf)); + cf->pattern = pathpart; + cf->pbuf = &casebuf; + add_visitor(visit_substring_match_casefold, cf); + /* If we ignore case, convert it to lower now so we don't have to + * do it every time + */ + lc_strcpy(pathpart, pathpart); + } else - count += c; - - /* Overlay the old path with the remainder of the new. */ - nread = getstr (&path, &pathsize, fp, '\0', count); - if (nread < 0) - break; - c = getc (fp); - s = path + count + nread - 2; /* Move to the last char in path. */ - assert (s[0] != '\0'); - assert (s[1] == '\0'); /* Our terminator. */ - assert (s[2] == '\0'); /* Added by getstr. */ + { + add_visitor(visit_substring_match_nocasefold, pathpart); + } } - - /* If the previous path matched, scan the whole path for the last - char in the subpattern. If not, the shared prefix doesn't match - the pattern, so don't scan it for the last char. */ - cutoff = prev_fast_match ? path : path + count; - - /* Search backward starting at the end of the path we just read in, - for the character at the end of the last glob-free subpattern - in PATHPART. */ - for (prev_fast_match = false; s >= cutoff; s--) - /* Fast first char check. */ - if (*s == *patend) - { - char *s2; /* Scan the path we read in. */ - register char *p2; /* Scan `patend'. */ - - for (s2 = s - 1, p2 = patend - 1; *p2 != '\0' && *s2 == *p2; - s2--, p2--) - ; - if (*p2 == '\0') - { - /* Success on the fast match. Compare the whole pattern - if it contains globbing characters. */ - prev_fast_match = true; - if (globflag == false || fnmatch (pathpart, path, 0) == 0) - { - puts (path); - ++printed; - } - break; - } - } } - if (ferror (fp)) + pvis = lastinspector; + + /* We add visit_existing_*() as late as possible to reduce the + * number of stat() calls. + */ + switch (check_existence) { - error (0, errno, "%s", dbfile); + case ACCEPT_EXISTING: + if (follow_symlinks) /* -L, default */ + add_visitor(visit_existing_follow, NULL); + else /* -P */ + add_visitor(visit_existing_nofollow, NULL); + break; + + case ACCEPT_NON_EXISTING: + if (follow_symlinks) /* -L, default */ + add_visitor(visit_non_existing_follow, NULL); + else /* -P */ + add_visitor(visit_non_existing_nofollow, NULL); + break; + + case ACCEPT_EITHER: /* Default, neither -E nor -e */ + /* do nothing; no extra processing. */ + break; + } + + if (stats) + add_visitor(visit_stats, &statistics); + + if (enable_print) + { + if (print_quoted_filename) + add_visitor(visit_justprint_quoted, NULL); + else + add_visitor(visit_justprint_unquoted, NULL); + } + + + if (use_limit) + add_visitor(visit_limit, plimit); + else + add_visitor(visit_count, plimit); + + + if (argc > 1) + { + past_pat_inspector = pvis->next; + if (op_and) + mainprocessor = process_and; + else + mainprocessor = process_or; + } + else + mainprocessor = process_simple; + + if (stats) + { + printf(_("Database %s is in the %s format.\n"), + procdata.dbfile, + old_format ? _("old") : "LOCATE02"); + } + + + procdata.c = getc (procdata.fp); + /* If we are searching for filename patterns, the inspector list + * will contain an entry for each pattern for which we are searching. + */ + while ( (procdata.c != EOF) && + (VISIT_ABORT != (mainprocessor)(&procdata)) ) + { + /* Do nothing; all the work is done in the visitor functions. */ + } + + if (stats) + { + print_stats(argc, st.st_size); + } + + if (ferror (procdata.fp)) + { + error (0, errno, "%s", procdata.dbfile); return 0; } - if (fclose (fp) == EOF) + if (procdata.fp != stdin && fclose (procdata.fp) == EOF) { error (0, errno, "%s", dbfile); return 0; } - return printed; + return plimit->items_accepted; } + + + extern char *version_string; /* The name this program was run with. */ char *program_name; static void -usage (stream, status) - FILE *stream; - int status; +usage (FILE *stream) { - fprintf (stream, "\ -Usage: %s [-d path] [--database=path] [--version] [--help] pattern...\n", + fprintf (stream, _("\ +Usage: %s [-d path | --database=path] [-e | -E | --[non-]existing]\n\ + [-i | --ignore-case] [-w | --wholename] [-b | --basename] \n\ + [--limit=N | -l N] [-S | --statistics] [-0 | --null] [-c | --count]\n\ + [-P | -H | --nofollow] [-L | --follow] [-m | --mmap ] [ -s | --stdio ]\n\ + [-A | --all] [-p | --print] [-r | --regex ] [--regextype=TYPE]\n\ + [--version] [--help]\n\ + pattern...\n"), program_name); - exit (status); + fputs (_("\nReport bugs to .\n"), stream); } +enum + { + REGEXTYPE_OPTION = CHAR_MAX + 1 + }; + static struct option const longopts[] = { {"database", required_argument, NULL, 'd'}, + {"existing", no_argument, NULL, 'e'}, + {"non-existing", no_argument, NULL, 'E'}, + {"ignore-case", no_argument, NULL, 'i'}, + {"all", no_argument, NULL, 'A'}, {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'v'}, + {"null", no_argument, NULL, '0'}, + {"count", no_argument, NULL, 'c'}, + {"wholename", no_argument, NULL, 'w'}, + {"wholepath", no_argument, NULL, 'w'}, /* Synonym. */ + {"basename", no_argument, NULL, 'b'}, + {"print", no_argument, NULL, 'p'}, + {"stdio", no_argument, NULL, 's'}, + {"mmap", no_argument, NULL, 'm'}, + {"limit", required_argument, NULL, 'l'}, + {"regex", no_argument, NULL, 'r'}, + {"regextype", required_argument, NULL, REGEXTYPE_OPTION}, + {"statistics", no_argument, NULL, 'S'}, + {"follow", no_argument, NULL, 'L'}, + {"nofollow", no_argument, NULL, 'P'}, {NULL, no_argument, NULL, 0} }; -void -main (argc, argv) - int argc; - char **argv; +int +main (int argc, char **argv) { char *dbpath; - int found = 0, optc; - + unsigned long int found = 0uL; + int ignore_case = 0; + int print = 0; + int just_count = 0; + int basename_only = 0; + int use_limit = 0; + int regex = 0; + int regex_options = RE_SYNTAX_EMACS; + int stats = 0; + int op_and = 0; + char *e; + program_name = argv[0]; +#ifdef HAVE_SETLOCALE + setlocale (LC_ALL, ""); +#endif + bindtextdomain (PACKAGE, LOCALEDIR); + textdomain (PACKAGE); + atexit (close_stdout); + + limits.limit = 0; + limits.items_accepted = 0; + + quote_opts = clone_quoting_options (NULL); + print_quoted_filename = true; + dbpath = getenv ("LOCATE_PATH"); if (dbpath == NULL) dbpath = LOCATE_DB; - while ((optc = getopt_long (argc, argv, "d:", longopts, (int *) 0)) != -1) - switch (optc) - { - case 'd': - dbpath = optarg; + check_existence = ACCEPT_EITHER; + + for (;;) + { + int opti = -1; + int optc = getopt_long (argc, argv, "Abcd:eEil:prsm0SwHPL", longopts, + &opti); + if (optc == -1) break; - case 'h': - usage (stdout, 0); + switch (optc) + { + case '0': + separator = 0; + print_quoted_filename = false; /* print filename 'raw'. */ + break; - case 'v': - printf ("GNU locate version %s\n", version_string); - exit (0); + case 'A': + op_and = 1; + break; - default: - usage (stderr, 1); - } + case 'b': + basename_only = 1; + break; - if (optind == argc) - usage (stderr, 1); + case 'c': + just_count = 1; + break; - for (; optind < argc; optind++) - { - char *e; - next_element (dbpath); /* Initialize. */ - while ((e = next_element ((char *) NULL)) != NULL) - found |= locate (argv[optind], e); + case 'd': + dbpath = optarg; + break; + + case 'e': + check_existence = ACCEPT_EXISTING; + break; + + case 'E': + check_existence = ACCEPT_NON_EXISTING; + break; + + case 'i': + ignore_case = 1; + break; + + case 'h': + usage (stdout); + return 0; + + case 'p': + print = 1; + break; + + case 'v': + printf (_("GNU locate version %s\n"), version_string); + printf (_("Built using GNU gnulib version %s\n"), gnulib_version); + return 0; + + case 'w': + basename_only = 0; + break; + + case 'r': + regex = 1; + break; + + case REGEXTYPE_OPTION: + regex_options = get_regex_type (optarg); + break; + + case 'S': + stats = 1; + break; + + case 'L': + follow_symlinks = 1; + break; + + /* In find, -P and -H differ in the way they handle paths + * given on the command line. This is not relevant for + * locate, but the -H option is supported because it is + * probably more intuitive to do so. + */ + case 'P': + case 'H': + follow_symlinks = 0; + break; + + case 'l': + { + char *end = optarg; + strtol_error err = xstrtoumax (optarg, &end, 10, &limits.limit, + NULL); + if (LONGINT_OK != err) + xstrtol_fatal (err, opti, optc, longopts, optarg); + use_limit = 1; + } + break; + + case 's': /* use stdio */ + case 'm': /* use mmap */ + /* These options are implemented simply for + * compatibility with FreeBSD + */ + break; + + default: + usage (stderr); + return 1; + } } - exit (!found); + if (!just_count && !stats) + print = 1; + + if (stats) + { + if (optind == argc) + use_limit = 0; + } + else + { + if (!just_count && optind == argc) + { + usage (stderr); + return 1; + } + } + + + if (1 == isatty(STDOUT_FILENO)) + stdout_is_a_tty = true; + else + stdout_is_a_tty = false; + + next_element (dbpath, 0); /* Initialize. */ + + /* Bail out early if limit already reached. */ + while ((e = next_element ((char *) NULL, 0)) != NULL && + (!use_limit || limits.limit > limits.items_accepted)) + { + statistics.compressed_bytes = + statistics.total_filename_count = + statistics.total_filename_length = + statistics.whitespace_count = + statistics.newline_count = + statistics.highbit_filename_count = 0u; + + if (0 == strlen(e) || 0 == strcmp(e, ".")) + { + /* Use the default database name instead (note: we + * don't use 'dbpath' since that might itself contain a + * colon-separated list. + */ + e = LOCATE_DB; + } + + found = locate (argc - optind, &argv[optind], e, ignore_case, print, basename_only, use_limit, &limits, stats, op_and, regex, regex_options); + } + + if (just_count) + { + printf("%ld\n", found); + } + + if (found || (use_limit && (limits.limit==0)) || stats ) + return 0; + else + return 1; } diff --git a/src/bin/findutils/locate/locatedb.5 b/src/bin/findutils/locate/locatedb.5 index 7145feef19..80360493dc 100644 --- a/src/bin/findutils/locate/locatedb.5 +++ b/src/bin/findutils/locate/locatedb.5 @@ -1,4 +1,4 @@ -.TH LOCATEDB 5L \" -*- nroff -*- +.TH LOCATEDB 5 \" -*- nroff -*- .SH NAME locatedb \- front-compressed file name database .SH DESCRIPTION @@ -10,12 +10,12 @@ particular directory trees when the databases were last updated. .P There can be multiple databases. Users can select which databases \fBlocate\fP searches using an environment variable or command line -option; see \fBlocate\fP(1L). The system administrator can choose the +option; see \fBlocate\fP(1). The system administrator can choose the file name of the default database, the frequency with which the databases are updated, and the directories for which they contain entries. Normally, file name databases are updated by running the \fBupdatedb\fP program periodically, typically nightly; see -\fBupdatedb\fP(1L). +\fBupdatedb\fP(1). .P \fBupdatedb\fP runs a program called \fBfrcode\fP to compress the list of file names using front-compression, which reduces @@ -102,5 +102,15 @@ and count bytes made printable: (6 = 14 \- 8, and \-9 = 5 \- 14) .fi .SH "SEE ALSO" -\fBfind\fP(1L), \fBlocate\fP(1L), \fBlocatedb\fP(5L), \fBxargs\fP(1L) +\fBfind\fP(1), \fBlocate\fP(1), \fBlocatedb\fP(5), \fBxargs\fP(1) \fBFinding Files\fP (on-line in Info, or printed) +.SH "BUGS" +.P +The best way to report a bug is to use the form at +http://savannah.gnu.org/bugs/?group=findutils. +The reason for this is that you will then be able to track progress in +fixing the problem. Other comments about \fBlocate\fP(1) and about +the findutils package in general can be sent to the +.I bug-findutils +mailing list. To join the list, send email to +.IR bug-findutils-request@gnu.org . diff --git a/src/bin/findutils/locate/locatedb.h b/src/bin/findutils/locate/locatedb.h index e4017651ee..1bd9bd6845 100644 --- a/src/bin/findutils/locate/locatedb.h +++ b/src/bin/findutils/locate/locatedb.h @@ -1,19 +1,19 @@ /* locatedb.h -- declarations for the locate database - Copyright (C) 1994 Free Software Foundation, Inc. + Copyright (C) 1994, 2003, 2006 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ #ifndef _LOCATEDB_H #define _LOCATEDB_H 1 @@ -30,6 +30,21 @@ This value (which is -128) indicates that the difference is too large to fit into one byte, and a two-byte integer follows. */ #define LOCATEDB_ESCAPE 0x80 +#define LOCATEDB_ONEBYTE_MAX (127) +#define LOCATEDB_ONEBYTE_MIN (-127) + + +/* If it is ever possible to try to encode LOCATEDB_MAGIC as a + * single-byte offset, then an unfortunate length of common prefix + * will produce a spurious escape character, desynchronising the data + * stream. We use a compile-time check in the preprocessor to prevent + * this. + */ +#if LOCATEDB_ESCAPE <= LOCATEDB_ONEBYTE_MAX +#error "You have a bad combination of LOCATEDB_ESCAPE and LOCATEDB_ONEBYTE_MAX, see above" +#endif + + /* These are used for old, bigram-encoded databases: */ @@ -39,4 +54,12 @@ /* Offset added to differential counts to encode them as positive numbers. */ #define LOCATEDB_OLD_OFFSET 14 +# ifndef PARAMS +# if defined PROTOTYPES || (defined __STDC__ && __STDC__) +# define PARAMS(Args) Args +# else +# define PARAMS(Args) () +# endif +# endif + #endif /* !_LOCATEDB_H */ diff --git a/src/bin/findutils/locate/updatedb.1 b/src/bin/findutils/locate/updatedb.1 index 767262620d..da84b8f4a0 100644 --- a/src/bin/findutils/locate/updatedb.1 +++ b/src/bin/findutils/locate/updatedb.1 @@ -1,4 +1,4 @@ -.TH UPDATEDB 1L \" -*- nroff -*- +.TH UPDATEDB 1 \" -*- nroff -*- .SH NAME updatedb \- update a file name database .SH SYNOPSIS @@ -23,56 +23,107 @@ the root of each filesystem, containing the entries for that filesystem. is then run for each filesystem on the fileserver where that filesystem is on a local disk, to prevent thrashing the network. Users can select which databases \fBlocate\fP searches using an -environment variable or command line option; see \fBlocate\fP(1L). +environment variable or command line option; see \fBlocate\fP(1). Databases can not be concatenated together. .P -The file name database format changed starting with GNU -.B find -and -.B locate -version 4.0 to allow machines with diffent byte orderings to share -the databases. The new GNU -.B locate -can read both the old and new database formats. -However, old versions of -.B locate -and -.B find -produce incorrect results if given a new-format database. +Versions of locate prior to 4.2.31 fail to correctly handle long file +names in the old databse format, but the default database format +(called LOCATE02) is not affected by this problem. All versions of +.B locate +since version 4.0 support the new LOCATE02 format. The old database +format also cannot correctly represent non-ASCII characters. .SH OPTIONS .TP +.B \-\-findoptions='\fI\-option1 \-option2...\fP' +Global options to pass on to \fBfind\fP. +The environment variable \fBFINDOPTIONS\fP also sets this value. +Default is none. +.TP .B \-\-localpaths='\fIpath1 path2...\fP' Non-network directories to put in the database. Default is /. .TP .B \-\-netpaths='\fIpath1 path2...\fP' Network (NFS, AFS, RFS, etc.) directories to put in the database. +The environment variable \fBNETPATHS\fP also sets this value. Default is none. .TP .B \-\-prunepaths='\fIpath1 path2...\fP' Directories to not put in the database, which would otherwise be. +Remove any trailing slashes from the path names, otherwise +.B updatedb +won\'t recognise the paths you want to omit (because it uses them as +regular expression patterns). +The environment variable \fBPRUNEPATHS\fP also sets this value. Default is /tmp /usr/tmp /var/tmp /afs. .TP +.B \-\-prunefs='\fIpath...\fP' +File systems to not put in the database, which would otherwise be. +Note that files are pruned when a file system is reached; +Any file system mounted under an undesired file system will be +ignored. +The environment variable +\fBPRUNEFS\fP also sets this value. +Default is \fInfs NFS proc\fP. +.TP .B \-\-output=\fIdbfile\fP The database file to build. -Default is system-dependent, but typically /usr/local/var/locatedb. +Default is system-dependent. In Debian GNU/Linux, the default +is /var/cache/locate/locatedb. +.TP +.B \-\-localuser=\fIuser\fP +The user to search non-network directories as, using \fBsu\fP(1). +Default is to search the non-network directories as the current user. +You can also use the environment variable \fBLOCALUSER\fP to set this user. .TP .B \-\-netuser=\fIuser\fP The user to search network directories as, using \fBsu\fP(1). Default is \fBdaemon\fP. +You can also use the environment variable \fBNETUSER\fP to set this user. .TP .B \-\-old\-format -Create the database in the old format instead of the new one. +Create the database in the old format instead of the new one. Avoid +using this option as older versions of locate are susceptible to a +buffer overrun when reading old-format databases. The old fatabase +format is also incapable of correctly representing non-ASCII +characters. .TP .B \-\-version Print the version number of .B updatedb and exit. .TP -.I "\-\-help" +.B "\-\-help" Print a summary of the options to .B updatedb and exit. .SH "SEE ALSO" -\fBfind\fP(1L), \fBlocate\fP(1L), \fBlocatedb\fP(5L), \fBxargs\fP(1L) +\fBfind\fP(1), \fBlocate\fP(1), \fBlocatedb\fP(5), \fBxargs\fP(1) \fBFinding Files\fP (on-line in Info, or printed) +.SH "BUGS" +.P +All versions of GNU locate prior to 4.2.31 fail to correctly handle +long (roughly, over 1024 bytes) filenames in old-format databases. +This can lead to a heap buffer overrun and it a potential security +issue. Verions 4.3.0 to 4.3.6 are also affected by the bug. +Databases in the default LOCATE02 format are correctly handled. +.P +The +.B updatedb +program correctly handles filenames containing newlines, +but only if the system's sort command has a working +.I \-z +option. If you suspect that +.B locate +may need to return filenames containing newlines, consider using its +.I \-\-null +option. +.P +The best way to report a bug is to use the form at +http://savannah.gnu.org/bugs/?group=findutils. +The reason for this is that you will then be able to track progress in +fixing the problem. Other comments about \fBupdatedb\fP(1) and about +the findutils package in general can be sent to the +.I bug-findutils +mailing list. To join the list, send email to +.IR bug-findutils-request@gnu.org . diff --git a/src/bin/findutils/locate/updatedb.sh b/src/bin/findutils/locate/updatedb.sh index 944791af17..59e03719da 100644 --- a/src/bin/findutils/locate/updatedb.sh +++ b/src/bin/findutils/locate/updatedb.sh @@ -1,41 +1,53 @@ -#!/bin/sh +#! /bin/sh # updatedb -- build a locate pathname database -# Copyright (C) 1994 Free Software Foundation, Inc. - -# This program is free software; you can redistribute it and/or modify +# Copyright (C) 1994, 1996, 1997, 2000, 2001, 2003, 2004, 2005, 2006 +# Free Software Foundation, Inc. +# +# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2, or (at your option) -# any later version. - +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. - +# # You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +# along with this program. If not, see . # csh original by James Woods; sh conversion by David MacKenzie. usage="\ -Usage: updatedb [--localpaths='dir1 dir2...'] [--netpaths='dir1 dir2...'] - [--prunepaths='dir1 dir2...'] [--output=dbfile] [--netuser=user] - [--old-format] [--version] [--help]" +Usage: $0 [--findoptions='-option1 -option2...'] + [--localpaths='dir1 dir2...'] [--netpaths='dir1 dir2...'] + [--prunepaths='dir1 dir2...'] [--prunefs='fs1 fs2...'] + [--output=dbfile] [--netuser=user] [--localuser=user] + [--old-format] [--version] [--help] +Report bugs to ." +changeto=/ old=no for arg do - opt=`echo $arg|sed 's/^\([^=]*\).*/\1/'` - val=`echo $arg|sed 's/^[^=]*=\(.*\)/\1/'` + # If we are unable to fork, the back-tick operator will + # fail (and the shell will emit an error message). When + # this happens, we exit with error value 71 (EX_OSERR). + # Alternative candidate - 75, EX_TEMPFAIL. + opt=`echo $arg|sed 's/^\([^=]*\).*/\1/'` || exit 71 + val=`echo $arg|sed 's/^[^=]*=\(.*\)/\1/'` || exit 71 case "$opt" in + --findoptions) FINDOPTIONS="$val" ;; --localpaths) SEARCHPATHS="$val" ;; --netpaths) NETPATHS="$val" ;; --prunepaths) PRUNEPATHS="$val" ;; + --prunefs) PRUNEFS="$val" ;; --output) LOCATE_DB="$val" ;; --netuser) NETUSER="$val" ;; + --localuser) LOCALUSER="$val" ;; --old-format) old=yes ;; - --version) echo "GNU updatedb version @version@"; exit 0 ;; + --changecwd) changeto="$val" ;; + --version) echo "GNU updatedb version @VERSION@"; exit 0 ;; --help) echo "$usage"; exit 0 ;; *) echo "updatedb: invalid option $opt $usage" >&2 @@ -43,9 +55,59 @@ $usage" >&2 esac done +if test "$old" = yes; then + echo "Warning: future versions of findutils will shortly discontinue support for the old locate database format." >&2 + + sort="@SORT@" + print_option="-print" + frcode_options="" +else + if @SORT_SUPPORTS_Z@ + then + sort="@SORT@ -z" + print_option="-print0" + frcode_options="-0" + else + sort="@SORT@" + print_option="-print" + frcode_options="" + fi +fi + +getuid() { + # format of "id" output is ... + # uid=1(daemon) gid=1(other) + # for `id's that don't understand -u + id | cut -d'(' -f 1 | cut -d'=' -f2 +} + +# figure out if su supports the -s option +select_shell() { + if su "$1" -s $SHELL -c false < /dev/null ; then + # No. + echo "" + else + if su "$1" -s $SHELL -c true < /dev/null ; then + # Yes. + echo "-s $SHELL" + else + # su is unconditionally failing. We won't be able to + # figure out what is wrong, so be conservative. + echo "" + fi + fi +} + + # You can set these in the environment, or use command-line options, # to override their defaults: +# Any global options for find? +: ${FINDOPTIONS=} + +# What shell shoud we use? We should use a POSIX-ish sh. +: ${SHELL="/bin/sh"} + # Non-network directories to put in the database. : ${SEARCHPATHS="/"} @@ -53,7 +115,17 @@ done : ${NETPATHS=} # Directories to not put in the database, which would otherwise be. -: ${PRUNEPATHS="/tmp /usr/tmp /var/tmp /afs"} +: ${PRUNEPATHS="/tmp /usr/tmp /var/tmp /afs /amd /sfs"} + +# Trailing slashes result in regex items that are never matched, which +# is not what the user will expect. Therefore we now reject such +# constructs. +for p in $PRUNEPATHS; do + case "$p" in + /*/) echo "$0: $p: pruned paths should not contain trailing slashes" >&2 + exit 1 + esac +done # The same, in the form of a regex that find can use. test -z "$PRUNEREGEX" && @@ -65,44 +137,97 @@ test -z "$PRUNEREGEX" && # Directory to hold intermediate files. if test -d /var/tmp; then : ${TMPDIR=/var/tmp} -else +elif test -d /usr/tmp; then : ${TMPDIR=/usr/tmp} +else + : ${TMPDIR=/tmp} fi +export TMPDIR # The user to search network directories as. : ${NETUSER=daemon} # The directory containing the subprograms. -: ${LIBEXECDIR=@libexecdir@} +if test -n "$LIBEXECDIR" ; then + : LIBEXECDIR already set, do nothing +else + : ${LIBEXECDIR=@libexecdir@} +fi # The directory containing find. -: ${BINDIR=@bindir@} +if test -n "$BINDIR" ; then + : BINDIR already set, do nothing +else + : ${BINDIR=@bindir@} +fi # The names of the utilities to run to build the database. -: ${find=@find@} -: ${frcode=@frcode@} -: ${bigram=@bigram@} -: ${code=@code@} +: ${find:=${BINDIR}/@find@} +: ${frcode:=${LIBEXECDIR}/@frcode@} +: ${bigram:=${LIBEXECDIR}/@bigram@} +: ${code:=${LIBEXECDIR}/@code@} -PATH=$LIBEXECDIR:$BINDIR:/usr/ucb:/bin:/usr/bin:$PATH export PATH + +PATH=/bin:/usr/bin:${BINDIR}; export PATH + +: ${PRUNEFS="nfs NFS proc afs proc smbfs autofs iso9660 ncpfs coda devpts ftpfs devfs mfs sysfs shfs"} + +if test -n "$PRUNEFS"; then +prunefs_exp=`echo $PRUNEFS |sed -e 's/\([^ ][^ ]*\)/-o -fstype \1/g' \ + -e 's/-o //' -e 's/$/ -o/'` +else + prunefs_exp='' +fi # Make and code the file list. # Sort case insensitively for users' convenience. +rm -f $LOCATE_DB.n +trap 'rm -f $LOCATE_DB.n; exit' HUP TERM + if test $old = no; then # FIXME figure out how to sort null-terminated strings, and use -print0. -{ +if { +cd "$changeto" if test -n "$SEARCHPATHS"; then - $find $SEARCHPATHS \ - \( -fstype nfs -o -fstype NFS -o -type d -regex "$PRUNEREGEX" \) -prune -o -print + if [ "$LOCALUSER" != "" ]; then + # : A1 + su $LOCALUSER `select_shell $LOCALUSER` -c \ + "$find $SEARCHPATHS $FINDOPTIONS \ + \\( $prunefs_exp \ + -type d -regex '$PRUNEREGEX' \\) -prune -o $print_option" + else + # : A2 + $find $SEARCHPATHS $FINDOPTIONS \ + \( $prunefs_exp \ + -type d -regex "$PRUNEREGEX" \) -prune -o $print_option + fi fi if test -n "$NETPATHS"; then - su $NETUSER -c \ - "$find $NETPATHS \\( -type d -regex \"$PRUNEREGEX\" -prune \\) -o -print" +myuid=`getuid` +if [ "$myuid" = 0 ]; then + # : A3 + su $NETUSER `select_shell $NETUSER` -c \ + "$find $NETPATHS $FINDOPTIONS \\( -type d -regex '$PRUNEREGEX' -prune \\) -o $print_option" || + exit $? + else + # : A4 + $find $NETPATHS $FINDOPTIONS \( -type d -regex "$PRUNEREGEX" -prune \) -o $print_option || + exit $? + fi +fi +} | $sort -f | $frcode $frcode_options > $LOCATE_DB.n +then + # OK so far + true +else + rv=$? + echo "Failed to generate $LOCATE_DB.n" >&2 + rm -f $LOCATE_DB.n + exit $rv fi -} | sort -f | $frcode > $LOCATE_DB.n # To avoid breaking locate while this script is running, put the # results in a temp file, then rename it atomically. @@ -117,32 +242,74 @@ fi else # old -bigrams=$TMPDIR/f.bigrams$$ -filelist=$TMPDIR/f.list$$ -trap 'rm -f $bigrams $filelist; exit' 1 15 +if ! bigrams=`mktemp -t updatedbXXXXXXXXX`; then + echo tempfile failed + exit 1 +fi -# Alphabetize subdirectories before file entries using tr. James says: +if ! filelist=`mktemp -t updatedbXXXXXXXXX`; then + echo tempfile failed + exit 1 +fi + +rm -f $LOCATE_DB.n +trap 'rm -f $bigrams $filelist $LOCATE_DB.n; exit' HUP TERM + +# Alphabetize subdirectories before file entries using tr. James Woods says: # "to get everything in monotonic collating sequence, to avoid some # breakage i'll have to think about." { +cd "$changeto" if test -n "$SEARCHPATHS"; then - $find $SEARCHPATHS \ - \( -fstype nfs -o -fstype NFS -o -type d -regex "$PRUNEREGEX" \) -prune -o -print + if [ "$LOCALUSER" != "" ]; then + # : A5 + su $LOCALUSER `select_shell $LOCALUSER` -c \ + "$find $SEARCHPATHS $FINDOPTIONS \ + \( $prunefs_exp \ + -type d -regex '$PRUNEREGEX' \) -prune -o $print_option" || exit $? + else + # : A6 + $find $SEARCHPATHS $FINDOPTIONS \ + \( $prunefs_exp \ + -type d -regex "$PRUNEREGEX" \) -prune -o $print_option || exit $? + fi fi + if test -n "$NETPATHS"; then - su $NETUSER -c \ - "$find $NETPATHS \\( -type d -regex \"$PRUNEREGEX\" -prune \\) -o -print" + myuid=`getuid` + if [ "$myuid" = 0 ]; then + # : A7 + su $NETUSER `select_shell $NETUSER` -c \ + "$find $NETPATHS $FINDOPTIONS \\( -type d -regex '$PRUNEREGEX' -prune \\) -o $print_option" || + exit $? + else + # : A8 + $find $NETPATHS $FINDOPTIONS \( -type d -regex "$PRUNEREGEX" -prune \) -o $print_option || + exit $? + fi fi -} | tr / '\001' | sort -f | tr '\001' / > $filelist +} | tr / '\001' | $sort -f | tr '\001' / > $filelist # Compute the (at most 128) most common bigrams in the file list. -$bigram < $filelist | sort | uniq -c | sort -nr | +$bigram $bigram_opts < $filelist | sort | uniq -c | sort -nr | awk '{ if (NR <= 128) print $2 }' | tr -d '\012' > $bigrams # Code the file list. -$code $bigrams < $filelist > $LOCATE_DB -chmod 644 $LOCATE_DB +$code $bigrams < $filelist > $LOCATE_DB.n -rm -f $bigrams $filelist $errs +rm -f $bigrams $filelist + +# To reduce the chances of breaking locate while this script is running, +# put the results in a temp file, then rename it atomically. +if test -s $LOCATE_DB.n; then + rm -f $LOCATE_DB + mv $LOCATE_DB.n $LOCATE_DB + chmod 644 $LOCATE_DB +else + echo "updatedb: new database would be empty" >&2 + rm -f $LOCATE_DB.n +fi fi + +exit 0 diff --git a/src/bin/findutils/xargs/Jamfile b/src/bin/findutils/xargs/Jamfile index 144d88f33f..d7230589c7 100644 --- a/src/bin/findutils/xargs/Jamfile +++ b/src/bin/findutils/xargs/Jamfile @@ -1,5 +1,6 @@ SubDir HAIKU_TOP src bin findutils xargs ; +SubDirSysHdrs [ FDirName $(SUBDIR) $(DOTDOT) gnulib lib ] ; SubDirSysHdrs [ FDirName $(SUBDIR) $(DOTDOT) lib ] ; SubDirSysHdrs [ FDirName $(SUBDIR) $(DOTDOT) ] ; @@ -14,6 +15,6 @@ TARGET_WARNING_CCFLAGS = [ FFilter $(TARGET_WARNING_CCFLAGS) BinCommand xargs : xargs.c - : libfindutils.a : findutils.rdef ; + : libfindutils.a gnulibfindutils.a : findutils.rdef ; SEARCH on [ FGristFiles findutils.rdef ] = [ FDirName $(SUBDIR) $(DOTDOT) ] ; diff --git a/src/bin/findutils/xargs/xargs.1 b/src/bin/findutils/xargs/xargs.1 index a9f39a7311..edbc4f6887 100644 --- a/src/bin/findutils/xargs/xargs.1 +++ b/src/bin/findutils/xargs/xargs.1 @@ -1,28 +1,206 @@ -.TH XARGS 1L \" -*- nroff -*- +.TH XARGS 1 \" -*- nroff -*- .SH NAME xargs \- build and execute command lines from standard input .SH SYNOPSIS .B xargs -[\-0prtx] [\-e[eof-str]] [\-i[replace-str]] [\-l[max-lines]] -[\-n max-args] [\-s max-chars] [\-P max-procs] [\-\-null] [\-\-eof[=eof-str]] -[\-\-replace[=replace-str]] [\-\-max-lines[=max-lines]] [\-\-interactive] -[\-\-max-chars=max-chars] [\-\-verbose] [\-\-exit] [\-\-max-procs=max-procs] -[\-\-max-args=max-args] [\-\-no-run-if-empty] [\-\-version] [\-\-help] +[\-0prtx] [\-E eof-str] [\-e[eof-str]] [\-\-eof[=eof-str]] [\-\-null] +[\-d delimiter] [\-\-delimiter delimiter] +[\-I replace-str] [\-i[replace-str]] [\-\-replace[=replace-str]] +[\-l[max-lines]] [\-L max-lines] [\-\-max\-lines[=max-lines]] [\-n max-args] [\-\-max\-args=max-args] +[\-s max-chars] [\-\-max\-chars=max-chars] [\-P max-procs] [\-\-max\-procs=max-procs] +[\-\-interactive] [\-\-verbose] [\-\-exit] [\-\-no\-run\-if\-empty] +[\-\-arg\-file=file] [\-\-show\-limits] [\-\-version] [\-\-help] [command [initial-arguments]] .SH DESCRIPTION This manual page documents the GNU version of .BR xargs . .B xargs -reads arguments from the standard input, delimited by blanks (which can be +reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the .I command (default is /bin/echo) one or more times with any .I initial-arguments -followed by arguments read from standard input. Blank lines on the +followed by items read from standard input. Blank lines on the standard input are ignored. .P +Because Unix filenames can contain blanks and newlines, this default +behaviour is often problematic; filenames containing blanks +and/or newlines are incorrectly processed by +.BR xargs . +In these situations it is better to use the `\-0' option, which +prevents such problems. When using this option you will need to +ensure that the program which produces the input for +.B xargs +also uses a null character as a separator. If that program is +GNU +.B find +for example, the `\-print0' option does this for you. +.P +If any invocation of the command exits with a status of 255, +.B xargs +will stop immediately without reading any further input. An error +message is issued on stderr when this happens. +.SS OPTIONS +.TP +.I "\-\-arg\-file=file, \-a file" +Read items from +.I file +instead of standard input. If you use this option, stdin remains +unchanged when commands are run. Otherwise, stdin is redirected +from +.IR /dev/null . + +.TP +.I "\-\-null, \-0" +Input items are terminated by a null character instead of by +whitespace, and the quotes and backslash are not special (every +character is taken literally). Disables the end of file string, which +is treated like any other argument. Useful when input items might +contain white space, quote marks, or backslashes. The GNU find +\-print0 option produces input suitable for this mode. +.TP +.I "\-\-delimiter=delim, \-d delim" +Input items are terminated by the specified character. Quotes and +backslash are not special; every character in the input is taken +literally. Disables the end-of-file string, which is treated like any +other argument. This can be used when the input consists of simply +newline-separated items, although it is almost always better to design +your program to use `\-\-null' where this is possible. The specified +delimiter may be a single character, a C-style character escape such +as +.BR \en , +or an octal or hexadecimal escape code. Octal and hexadecimal +escape codes are understood as for the +.B printf +command. Multibyte characters are not supported. + +.TP +.I "\-Eeof-str" +Set the end of file string to \fIeof-str\fR. If the end of file +string occurs as a line of input, the rest of the input is ignored. +If neither \-E nor \-e is used, no end of file string is used. +.TP +.I "\-\-eof[=eof-str], \-e[eof-str]" +This option is a synonym for the `\-E' option. Use `\-E' instead, +because it is POSIX compliant while this option is not. If +\fIeof-str\fR is omitted, there is no end of file string. If neither +\-E nor \-e is used, no end of file string is used. +.TP +.I "\-\-help" +Print a summary of the options to +.B xargs +and exit. +.TP +.I "\-I replace-str" +Replace occurrences of \fIreplace-str\fR in the initial-arguments with +names read from standard input. Also, unquoted blanks do not +terminate input items; instead the separator is the newline character. +Implies \fI\-x\fP and \fI\-L 1\fP. +.TP +.I "\-\-replace[=replace-str], \-i[replace-str]" +This option is a synonym for \-I\fIreplace-str\fR if \fIreplace-str\fR +is specified, and for \-I{} otherwise. This option is deprecated; use +\-I instead. +.TP +.I "\-L max-lines" +Use at most \fImax-lines\fR nonblank input lines per command line. +Trailing blanks cause an input line to be logically continued on the +next input line. Implies \fI\-x\fR. +.TP +.I "\-\-max-lines[=max-lines], \-l[max-lines]" +Synonym for the \-L option. Unlike \-L, the \fImax-lines\fR argument +is optional. If \fImax-args\fR is not specified, it defaults to one. +The \-l option is deprecated since the POSIX standard specifies \-L +instead. +.TP +.I "\-\-max\-args=max-args, \-n max-args" +Use at most \fImax-args\fR arguments per command line. Fewer than +\fImax-args\fR arguments will be used if the size (see the \-s option) +is exceeded, unless the \-x option is given, in which case \fBxargs\fR +will exit. +.TP +.I "\-\-interactive, \-p" +Prompt the user about whether to run each command line and read a line +from the terminal. Only run the command line if the response starts +with `y' or `Y'. Implies \fI\-t\fR. +.TP +.I "\-\-no\-run\-if\-empty, \-r" +If the standard input does not contain any nonblanks, do not run the +command. Normally, the command is run once even if there is no input. +This option is a GNU extension. +.TP +.I "\-\-max\-chars=max-chars, \-s max-chars" +Use at most \fImax-chars\fR characters per command line, including the +command and initial-arguments and the terminating nulls at the ends of +the argument strings. The default is 131072 characters, not including +the size of the environment variables (which are provided for +separately so that it doesn't matter if your environment variables +take up more than 131072 bytes). The operating system places limits +on the values that you can usefully specify, and if you exceed these a +warning message is printed and the value actually used is set to the +appropriate upper or lower limit. +.TP +.I "\-\-verbose, \-t" +Print the command line on the standard error output before executing +it. +.TP +.I "\-\-version" +Print the version number of +.B xargs +and exit. +.TP +.I "\-\-show\\-limits" +Display the limits on the command-line length which are imposed by the +operating system, +.BR xargs ' +choice of buffer size and the +.I \-s +option. Pipe the input from +.B /dev/null +(and perhaps specify +.BR --no-run-if-empty ) +if you don't want +.B xargs +to do anything. +.TP +.I "\-\-exit, \-x" +Exit if the size (see the \fI\-s\fR option) is exceeded. +.TP +.I "\-\-max\-procs=max-procs, \-P max-procs" +Run up to \fImax-procs\fR processes at a time; the default is 1. If +\fImax-procs\fR is 0, \fBxargs\fR will run as many processes as +possible at a time. Use the \fI\-n\fR option with \fI\-P\fR; +otherwise chances are that only one exec will be done. +.SH "EXAMPLES" +.nf +.B find /tmp \-name core \-type f \-print | xargs /bin/rm \-f + +.fi +Find files named +.B core +in or below the directory +.B /tmp +and delete them. Note that this will work incorrectly if there are +any filenames containing newlines or spaces. +.P +.B find /tmp \-name core \-type f \-print0 | xargs \-0 /bin/rm \-f + +.fi +Find files named +.B core +in or below the directory +.B /tmp +and delete them, processing filenames in such a way that file or +directory names containing spaces or newlines are correctly handled. +.P +.nf +.B cut \-d: \-f1 < /etc/passwd | sort | xargs echo + +.fi +Generates a compact listing of all the users on the system. +.SH "EXIT STATUS" .B xargs exits with the following status: .nf @@ -34,79 +212,75 @@ exits with the following status: 127 if the command is not found 1 if some other error occurred. .fi -.SS OPTIONS -.TP -.I "\-\-null, \-0" -Input filenames are terminated by a null character instead of by -whitespace, and the quotes and backslash are not special (every -character is taken literally). Disables the end of file string, which -is treated like any other argument. Useful when arguments might -contain white space, quote marks, or backslashes. The GNU find -\-print0 option produces input suitable for this mode. -.TP -.I "\-\-eof[=eof-str], \-e[eof-str]" -Set the end of file string to \fIeof-str\fR. If the end of file -string occurs as a line of input, the rest of the input is ignored. -If \fIeof-str\fR is omitted, there is no end of file string. If this -option is not given, the end of file string defaults to "_". -.TP -.I "\-\-help" -Print a summary of the options to +.P +Exit codes greater than 128 are used by the shell to indicate that +a program died due to a fatal signal. +.SH "STANDARDS CONFORMANCE" +As of GNU xargs version 4.2.9, the default behaviour of .B xargs -and exit. -.TP -.I "\-\-replace[=replace-str], \-i[replace-str]" -Replace occurences of \fIreplace-str\fR in the initial arguments with -names read from standard input. -Also, unquoted blanks do not terminate arguments. -If \fIreplace-str\fR is omitted, it -defaults to "{}" (like for `find \-exec'). Implies \fI\-x\fP and -\fI\-l 1\fP. -.TP -.I "\-\-max-lines[=max-lines], -l[max-lines]" -Use at most \fImax-lines\fR nonblank input lines per command line; -\fImax-lines\fR defaults to 1 if omitted. Trailing blanks cause an -input line to be logically continued on the next input line. Implies -\fI\-x\fR. -.TP -.I "\-\-max-args=max-args, \-n max-args" -Use at most \fImax-args\fR arguments per command line. Fewer than -\fImax-args\fR arguments will be used if the size (see the \-s option) -is exceeded, unless the \-x option is given, in which case \fBxargs\fR -will exit. -.TP -.I "\-\-interactive, \-p" -Prompt the user about whether to run each command line and read a line -from the terminal. Only run the command line if the response starts -with `y' or `Y'. Implies \fI\-t\fR. -.TP -.I "\-\-no-run-if-empty, \-r" -If the standard input does not contain any nonblanks, do not run the -command. Normally, the command is run once even if there is no input. -.TP -.I "\-\-max-chars=max-chars, \-s max-chars" -Use at most \fImax-chars\fR characters per command line, including the -command and initial arguments and the terminating nulls at the ends of -the argument strings. The default is as large as possible, up to 20k -characters. -.TP -.I "\-\-verbose, \-t" -Print the command line on the standard error output before executing -it. -.TP -.I "\-\-version" -Print the version number of -.B xargs -and exit. -.TP -.I "\-\-exit, \-x" -Exit if the size (see the \fI\-s\fR option) is exceeded. -.TP -.I "\-\-max-procs=max-procs, \-P max-procs" -Run up to \fImax-procs\fR processes at a time; the default is 1. If -\fImax-procs\fR is 0, \fBxargs\fR will run as many processes as -possible at a time. Use the \fI\-n\fR option with \fI\-P\fR; -otherwise chances are that only one exec will be done. +is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, +2004 Edition) allows this. +.P +The \-l and \-i options appear in the 1997 version of the POSIX +standard, but do not appear in the 2004 version of the standard. +Therefore you should use \-L and \-I instead, respectively. + .SH "SEE ALSO" -\fBfind\fP(1L), \fBlocate\fP(1L), \fBlocatedb\fP(5L), \fBupdatedb\fP(1) +\fBfind\fP(1), \fBlocate\fP(1), \fBlocatedb\fP(5), \fBupdatedb\fP(1), \fBFinding Files\fP (on-line in Info, or printed) +.SH "BUGS" +The \-L option is incompatible with the \-I option, but perhaps should not be. +.P +It is not possible for +.B xargs +to be used securely, since there will always be a time gap between the +production of the list of input files and their use in the commands +that +.B xargs +issues. If other users have access to the system, they can manipulate +the filesystem during this time window to force the action of the +commands +.B xargs +runs to apply to files that you didn't intend. For a more detailed +discussion of this and related problems, please refer to the +``Security Considerations'' chapter in the findutils Texinfo +documentation. The \-execdir option of +.B find +can often be used as a more secure alternative. + +When you use the \-I option, each line read from the input is buffered +internally. This means that there is an upper limit on the length +of input line that +.B xargs +will accept when used with the \-I option. To work around this +limitation, you can use the \-s option to increase the amount of +buffer space that +.B xargs +uses, and you can also use an extra invocation of +.B xargs +to ensure that very long lines do not occur. +For example: +.P +.B somecommand | xargs \-s 50000 echo | xargs \-I '{}' \-s 100000 rm '{}' +.P +Here, the first invocation of +.B xargs +has no input line length limit +because it doesn't use the \-i option. The second invocation of +.B xargs +does have such a limit, but we have ensured that the it never encounters +a line which is longer than it can handle. This is not an ideal +solution. Instead, the \-i option should not impose a line length +limit, which is why this discussion appears in the BUGS section. +The problem doesn't occur with the output of +.BR find (1) +because it emits just one filename per line. +.P +The best way to report a bug is to use the form at +http://savannah.gnu.org/bugs/?group=findutils. +The reason for this is that you will then be able to track progress in +fixing the problem. Other comments about \fBxargs\fP(1) and about +the findutils package in general can be sent to the +.I bug\-findutils +mailing list. To join the list, send email to +.IR bug\-findutils\-request@gnu.org . diff --git a/src/bin/findutils/xargs/xargs.c b/src/bin/findutils/xargs/xargs.c index 1a1e89d23b..6a530aa46e 100644 --- a/src/bin/findutils/xargs/xargs.c +++ b/src/bin/findutils/xargs/xargs.c @@ -1,32 +1,37 @@ /* xargs -- build and execute command lines from standard input - Copyright (C) 1990, 91, 92, 93, 94 Free Software Foundation, Inc. + Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + along with this program. If not, see . +*/ /* Written by Mike Rendell - and David MacKenzie . */ + and David MacKenzie . + Modifications by + James Youngman + Dmitry V. Levin +*/ #include -#if __STDC__ -#define P_(s) s -#else -#define P_(s) () -#endif +# ifndef PARAMS +# if defined PROTOTYPES || (defined __STDC__ && __STDC__) +# define PARAMS(Args) Args +# else +# define PARAMS(Args) () +# endif +# endif -#define _GNU_SOURCE #include #if !defined (isascii) || defined (STDC_HEADERS) @@ -49,6 +54,11 @@ #include #include #include +#include + +#if defined(STDC_HEADERS) +#include +#endif #if defined(HAVE_STRING_H) || defined(STDC_HEADERS) #include @@ -60,9 +70,6 @@ #define memcpy(dest, source, count) (bcopy((source), (dest), (count))) #endif -char *strstr (); -char *strdup (); - #ifndef _POSIX_SOURCE #include #endif @@ -71,25 +78,21 @@ char *strdup (); #include #endif -#ifdef HAVE_UNISTD_H -#include +#ifndef LONG_MAX +#define LONG_MAX (~(1 << (sizeof (long) * 8 - 1))) #endif +/* The presence of unistd.h is assumed by gnulib these days, so we + * might as well assume it too. + */ +#include + #include #if !defined(SIGCHLD) && defined(SIGCLD) #define SIGCHLD SIGCLD #endif -/* COMPAT: SYSV version defaults size (and has a max value of) to 470. - We try to make it as large as possible. */ -#if !defined(ARG_MAX) && defined(_SC_ARG_MAX) -#define ARG_MAX sysconf (_SC_ARG_MAX) -#endif -#ifndef ARG_MAX -#define ARG_MAX NCARGS -#endif - #include "wait.h" /* States for read_line. */ @@ -101,18 +104,54 @@ char *strdup (); #ifdef STDC_HEADERS #include #else -char *malloc (); -void exit (); -void free (); -long strtol (); - extern int errno; #endif +#ifdef HAVE_LOCALE_H +#include +#endif +#if ENABLE_NLS +# include +# define _(Text) gettext (Text) +#else +# define _(Text) Text +#define textdomain(Domain) +#define bindtextdomain(Package, Directory) +#endif +#ifdef gettext_noop +# define N_(String) gettext_noop (String) +#else +/* See locate.c for explanation as to why not use (String) */ +# define N_(String) String +#endif + +#include "buildcmd.h" + + /* Return nonzero if S is the EOF string. */ #define EOF_STR(s) (eof_str && *eof_str == *s && !strcmp (eof_str, s)) -extern char **environ; +/* Do multibyte processing if multibyte characters are supported, + unless multibyte sequences are search safe. Multibyte sequences + are search safe if searching for a substring using the byte + comparison function 'strstr' gives no false positives. All 8-bit + encodings and the UTF-8 multibyte encoding are search safe, but + the EUC encodings are not. + BeOS uses the UTF-8 encoding exclusively, so it is search safe. */ +#if defined __BEOS__ +# define MULTIBYTE_IS_SEARCH_SAFE 1 +#endif +#define DO_MULTIBYTE (HAVE_MBLEN && ! MULTIBYTE_IS_SEARCH_SAFE) + +#if DO_MULTIBYTE +# if HAVE_MBRLEN +# include +# else + /* Simulate mbrlen with mblen as best we can. */ +# define mbstate_t int +# define mbrlen(s, n, ps) mblen (s, n) +# endif +#endif /* Not char because of type promotion; NeXT gcc can't handle it. */ typedef int boolean; @@ -125,68 +164,40 @@ typedef int boolean; #define VOID char #endif -VOID *xmalloc P_ ((size_t n)); -VOID *xrealloc P_ ((VOID * p, size_t n)); -void error P_ ((int status, int errnum, char *message,...)); +#include +#include "closein.h" +#include "gnulib-version.h" + +void error PARAMS ((int status, int errnum, char *message,...)); extern char *version_string; /* The name this program was run with. */ char *program_name; -/* Buffer for reading arguments from stdin. */ +static FILE *input_stream; + +/* Buffer for reading arguments from input. */ static char *linebuf; +static int keep_stdin = 0; + /* Line number in stdin since the last command was executed. */ static int lineno = 0; -/* If nonzero, then instead of putting the args from stdin at - the end of the command argument list, they are each stuck into the - initial args, replacing each occurrence of the `replace_pat' in the - initial args. */ -static char *replace_pat = NULL; +static struct buildcmd_state bc_state; +static struct buildcmd_control bc_ctl; -/* The length of `replace_pat'. */ -static size_t rplen = 0; /* If nonzero, when this string is read on stdin it is treated as end of file. - I don't like this - it should default to NULL. */ -static char *eof_str = "_"; - -/* If nonzero, the maximum number of nonblank lines from stdin to use - per command line. */ -static long lines_per_exec = 0; - -/* The maximum number of arguments to use per command line. */ -static long args_per_exec = 1024; - -/* If true, exit if lines_per_exec or args_per_exec is exceeded. */ -static boolean exit_if_size_exceeded = false; - -/* The maximum number of characters that can be used per command line. */ -static long arg_max; - -/* Storage for elements of `cmd_argv'. */ -static char *argbuf; - -/* The list of args being built. */ -static char **cmd_argv = NULL; - -/* Number of elements allocated for `cmd_argv'. */ -static int cmd_argv_alloc = 0; - -/* Number of valid elements in `cmd_argv'. */ -static int cmd_argc = 0; - -/* Number of chars being used in `cmd_argv'. */ -static int cmd_argv_chars = 0; - -/* Number of initial arguments given on the command line. */ -static int initial_argc = 0; + IEEE Std 1003.1, 2004 Edition allows this to be NULL. + In findutils releases up to and including 4.2.8, this was "_". +*/ +static char *eof_str = NULL; /* Number of chars in the initial args. */ -static int initial_argv_chars = 0; +/* static int initial_argv_chars = 0; */ /* true when building up initial arguments in `cmd_argv'. */ static boolean initial_args = true; @@ -209,26 +220,37 @@ static int pids_alloc = 0; /* Exit status; nonzero if any child process exited with a status of 1-125. */ -static int child_error = 0; +static volatile int child_error = 0; + +static volatile int original_exit_value; /* If true, print each command on stderr before executing it. */ -static boolean print_command = false; +static boolean print_command = false; /* Option -t */ /* If true, query the user before executing each command, and only execute the command if the user responds affirmatively. */ static boolean query_before_executing = false; +/* The delimiter for input arguments. This is only consulted if the + * -0 or -d option had been given. + */ +static char input_delimiter = '\0'; + + static struct option const longopts[] = { {"null", no_argument, NULL, '0'}, + {"arg-file", required_argument, NULL, 'a'}, + {"delimiter", required_argument, NULL, 'd'}, {"eof", optional_argument, NULL, 'e'}, - {"replace", optional_argument, NULL, 'i'}, + {"replace", optional_argument, NULL, 'I'}, {"max-lines", optional_argument, NULL, 'l'}, {"max-args", required_argument, NULL, 'n'}, {"interactive", no_argument, NULL, 'p'}, {"no-run-if-empty", no_argument, NULL, 'r'}, {"max-chars", required_argument, NULL, 's'}, {"verbose", no_argument, NULL, 't'}, + {"show-limits", no_argument, NULL, 'S'}, {"exit", no_argument, NULL, 'x'}, {"max-procs", required_argument, NULL, 'P'}, {"version", no_argument, NULL, 'v'}, @@ -236,94 +258,292 @@ static struct option const longopts[] = {NULL, no_argument, NULL, 0} }; -static int read_line P_ ((void)); -static int read_string P_ ((void)); -static void do_insert P_ ((char *arg, size_t arglen, size_t lblen)); -static void push_arg P_ ((char *arg, size_t len)); -static boolean print_args P_ ((boolean ask)); -static void do_exec P_ ((void)); -static void add_proc P_ ((pid_t pid)); -static void wait_for_proc P_ ((boolean all)); -static long parse_num P_ ((char *str, int option, long min, long max)); -static long env_size P_ ((char **envp)); -static void usage P_ ((FILE * stream, int status)); +static int read_line PARAMS ((void)); +static int read_string PARAMS ((void)); +static boolean print_args PARAMS ((boolean ask)); +/* static void do_exec PARAMS ((void)); */ +static int xargs_do_exec (const struct buildcmd_control *cl, struct buildcmd_state *state); +static void exec_if_possible PARAMS ((void)); +static void add_proc PARAMS ((pid_t pid)); +static void wait_for_proc PARAMS ((boolean all)); +static void wait_for_proc_all PARAMS ((void)); +static long parse_num PARAMS ((char *str, int option, long min, long max, int fatal)); +static void usage PARAMS ((FILE * stream)); -void -main (argc, argv) - int argc; - char **argv; + + +static char +get_char_oct_or_hex_escape(const char *s) +{ + const char * p; + int base = 8; + unsigned long val; + char *endp; + + assert('\\' == s[0]); + + if ('x' == s[1]) + { + /* hex */ + p = s+2; + base = 16; + } + else if (isdigit(s[1])) + { + /* octal */ + p = s+1; + base = 8; + } + else + { + error(1, 0, + _("Invalid escape sequence %s in input delimiter specification."), + s); + } + errno = 0; + endp = (char*)p; + val = strtoul(p, &endp, base); + + /* This if condition is carefully constructed to do + * the right thing if UCHAR_MAX has the same + * value as ULONG_MAX. IF UCHAR_MAX==ULONG_MAX, + * then val can never be greater than UCHAR_MAX. + */ + if ((ULONG_MAX == val && ERANGE == errno) + || (val > UCHAR_MAX)) + { + if (16 == base) + { + error(1, 0, + _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lx."), + s, (unsigned long)UCHAR_MAX); + } + else + { + error(1, 0, + _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lo."), + s, (unsigned long)UCHAR_MAX); + } + } + + /* check for trailing garbage */ + if (0 != *endp) + { + error(1, 0, + _("Invalid escape sequence %s in input delimiter specification; trailing characters %s not recognised."), + s, endp); + } + + return (char) val; +} + + +static char +get_input_delimiter(const char *s) +{ + if (1 == strlen(s)) + { + return s[0]; + } + else + { + if ('\\' == s[0]) + { + /* an escape code */ + switch (s[1]) + { + case 'a': + return '\a'; + case 'b': + return '\b'; + case 'f': + return '\f'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 't': + return'\t'; + case 'v': + return '\v'; + case '\\': + return '\\'; + default: + return get_char_oct_or_hex_escape(s); + } + } + else + { + error(1, 0, + _("Invalid input delimiter specification %s: the delimiter must be either a single character or an escape sequence starting with \\."), + s); + abort (); + } + } +} + +static void +noop (void) +{ + /* does nothing. */ +} + +static void +fail_due_to_env_size (void) +{ + error (1, 0, _("environment is too large for exec")); +} + + +int +main (int argc, char **argv) { int optc; + int show_limits = 0; /* --show-limits */ int always_run_command = 1; - long orig_arg_max; + char *input_file = "-"; /* "-" is stdin */ char *default_cmd = "/bin/echo"; - int (*read_args) P_ ((void)) = read_line; + int (*read_args) PARAMS ((void)) = read_line; + void (*act_on_init_result)(void) = noop; + enum BC_INIT_STATUS bcstatus; program_name = argv[0]; + original_exit_value = 0; + +#ifdef HAVE_SETLOCALE + setlocale (LC_ALL, ""); +#endif + bindtextdomain (PACKAGE, LOCALEDIR); + textdomain (PACKAGE); + atexit (close_stdin); + atexit (wait_for_proc_all); - orig_arg_max = ARG_MAX - 2048; /* POSIX.2 requires subtracting 2048. */ - arg_max = orig_arg_max; - - /* Sanity check for systems with huge ARG_MAX defines (e.g., Suns which - have it at 1 meg). Things will work fine with a large ARG_MAX but it - will probably hurt the system more than it needs to; an array of this - size is allocated. */ - if (arg_max > 20 * 1024) - arg_max = 20 * 1024; - - /* Take the size of the environment into account. */ - arg_max -= env_size (environ); - if (arg_max <= 0) - error (1, 0, "environment is too large for exec"); - - while ((optc = getopt_long (argc, argv, "+0e::i::l::n:prs:txP:", + bcstatus = bc_init_controlinfo(&bc_ctl); + /* The bc_init_controlinfo call may have determined that the + * environment is too big. In that case, we will fail with + * an error message after processing the command-line options, + * as "xargs --help" should still work even if the environment is + * too big. + * + * Some of the argument processing depends on the contents of + * bc_ctl, which will be in an undefined state if bc_init_controlinfo() + * failed. + */ + if (BC_INIT_ENV_TOO_BIG == bcstatus) + { + act_on_init_result = fail_due_to_env_size; + } + else + { + /* IEEE Std 1003.1, 2003 specifies that the combined argument and + * environment list shall not exceed {ARG_MAX}-2048 bytes. It also + * specifies that it shall be at least LINE_MAX. + */ +#if defined(ARG_MAX) + assert(bc_ctl.arg_max <= (ARG_MAX-2048)); +#endif +#ifdef LINE_MAX + assert(bc_ctl.arg_max >= LINE_MAX); +#endif + + bc_ctl.exec_callback = xargs_do_exec; + + /* Start with a reasonable default size, though this can be + * adjusted via the -s option. + */ + bc_use_sensible_arg_max(&bc_ctl); + } + + while ((optc = getopt_long (argc, argv, "+0a:E:e::i::I:l::L:n:prs:txP:d:", longopts, (int *) 0)) != -1) { switch (optc) { case '0': read_args = read_string; + input_delimiter = '\0'; break; - case 'e': - if (optarg) + case 'd': + read_args = read_string; + input_delimiter = get_input_delimiter(optarg); + break; + + case 'E': /* POSIX */ + case 'e': /* deprecated */ + if (optarg && (strlen(optarg) > 0)) eof_str = optarg; else eof_str = 0; break; case 'h': - usage (stdout, 0); + usage (stdout); + return 0; - case 'i': + case 'I': /* POSIX */ + case 'i': /* deprecated */ if (optarg) - replace_pat = optarg; + bc_ctl.replace_pat = optarg; else - replace_pat = "{}"; + bc_ctl.replace_pat = "{}"; /* -i excludes -n -l. */ - args_per_exec = 0; - lines_per_exec = 0; + bc_ctl.args_per_exec = 0; + bc_ctl.lines_per_exec = 0; break; - case 'l': + case 'L': /* POSIX */ + bc_ctl.lines_per_exec = parse_num (optarg, 'L', 1L, -1L, 1); + /* -L excludes -i -n. */ + bc_ctl.args_per_exec = 0; + bc_ctl.replace_pat = NULL; + break; + + case 'l': /* deprecated */ if (optarg) - lines_per_exec = parse_num (optarg, 'l', 1L, -1L); + bc_ctl.lines_per_exec = parse_num (optarg, 'l', 1L, -1L, 1); else - lines_per_exec = 1; + bc_ctl.lines_per_exec = 1; /* -l excludes -i -n. */ - args_per_exec = 0; - replace_pat = NULL; + bc_ctl.args_per_exec = 0; + bc_ctl.replace_pat = NULL; break; case 'n': - args_per_exec = parse_num (optarg, 'n', 1L, -1L); + bc_ctl.args_per_exec = parse_num (optarg, 'n', 1L, -1L, 1); /* -n excludes -i -l. */ - lines_per_exec = 0; - replace_pat = NULL; + bc_ctl.lines_per_exec = 0; + if (bc_ctl.args_per_exec == 1 && bc_ctl.replace_pat) + /* ignore -n1 in '-i -n1' */ + bc_ctl.args_per_exec = 0; + else + bc_ctl.replace_pat = NULL; break; + /* The POSIX standard specifies that it is not an error + * for the -s option to specify a size that the implementation + * cannot support - in that case, the relevant limit is used. + */ case 's': - arg_max = parse_num (optarg, 's', 1L, orig_arg_max); + { + size_t arg_size; + act_on_init_result(); + arg_size = parse_num (optarg, 's', 1L, + bc_ctl.posix_arg_size_max, 0); + if (arg_size > bc_ctl.posix_arg_size_max) + { + error (0, 0, + _("warning: value %ld for -s option is too large, " + "using %ld instead"), + arg_size, bc_ctl.posix_arg_size_max); + arg_size = bc_ctl.posix_arg_size_max; + } + bc_ctl.arg_max = arg_size; + } + break; + + case 'S': + show_limits = true; break; case 't': @@ -331,7 +551,7 @@ main (argc, argv) break; case 'x': - exit_if_size_exceeded = true; + bc_ctl.exit_if_size_exceeded = true; break; case 'p': @@ -344,20 +564,52 @@ main (argc, argv) break; case 'P': - proc_max = parse_num (optarg, 'P', 0L, -1L); + proc_max = parse_num (optarg, 'P', 0L, -1L, 1); break; + case 'a': + input_file = optarg; + break; + case 'v': - printf ("GNU xargs version %s\n", version_string); - exit (0); + printf (_("GNU xargs version %s\n"), version_string); + printf (_("Built using GNU gnulib version %s\n"), gnulib_version); + return 0; default: - usage (stderr, 1); + usage (stderr); + return 1; } } - if (replace_pat || lines_per_exec) - exit_if_size_exceeded = true; + /* If we had deferred failing due to problems in bc_init_controlinfo(), + * do it now. + * + * We issue this error message after processing command line + * arguments so that it is possible to use "xargs --help" even if + * the environment is too large. + */ + act_on_init_result(); + assert(BC_INIT_OK == bcstatus); + + if (0 == strcmp (input_file, "-")) + { + input_stream = stdin; + } + else + { + keep_stdin = 1; /* see prep_child_for_exec() */ + input_stream = fopen (input_file, "r"); + if (NULL == input_stream) + { + error (1, errno, + _("Cannot open input file `%s'"), + input_file); + } + } + + if (bc_ctl.replace_pat || bc_ctl.lines_per_exec) + bc_ctl.exit_if_size_exceeded = true; if (optind == argc) { @@ -366,32 +618,82 @@ main (argc, argv) argv = &default_cmd; } - linebuf = (char *) xmalloc (arg_max + 1); - argbuf = (char *) xmalloc (arg_max + 1); + /* We want to be able to print size_t values as unsigned long, so if + * the cast isn't value-preserving, we have a problem. This isn't a + * problem in C89, because size_t was known to be no wider than + * unsigned long. In C99 this is no longer the case, but there are + * special C99 ways to print such values. Unfortunately this + * program tries to work on both C89 and C99 systems. + */ +#if defined(SIZE_MAX) +# if SIZE_MAX > ULONG_MAX +# error "I'm not sure how to print size_t values on your system" +# endif +#else + /* Without SIZE_MAX (i.e. limits.h) this is probably + * close to the best we can do. + */ + assert(sizeof(size_t) <= sizeof(unsigned long)); +#endif + + if (show_limits) + { + fprintf(stderr, + _("Your environment variables take up %lu bytes\n"), + (unsigned long)bc_size_of_environment()); + fprintf(stderr, + _("POSIX lower and upper limits on argument length: %lu, %lu\n"), + (unsigned long)bc_ctl.posix_arg_size_min, + (unsigned long)bc_ctl.posix_arg_size_max); + fprintf(stderr, + _("Maximum length of command we could actually use: %ld\n"), + (unsigned long)(bc_ctl.posix_arg_size_max - + bc_size_of_environment())); + fprintf(stderr, + _("Size of command buffer we are actually using: %lu\n"), + (unsigned long)bc_ctl.arg_max); + + if (isatty(STDIN_FILENO)) + { + fprintf(stderr, + "\n" + "Execution of xargs will continue now, and it will " + "try to read its input and run commands; if this is " + "not what you wanted to happen, please type the " + "end-of-file keystroke.\n"); + } + } + + linebuf = (char *) xmalloc (bc_ctl.arg_max + 1); + bc_state.argbuf = (char *) xmalloc (bc_ctl.arg_max + 1); /* Make sure to listen for the kids. */ signal (SIGCHLD, SIG_DFL); - if (!replace_pat) + if (!bc_ctl.replace_pat) { for (; optind < argc; optind++) - push_arg (argv[optind], strlen (argv[optind]) + 1); + bc_push_arg (&bc_ctl, &bc_state, + argv[optind], strlen (argv[optind]) + 1, + NULL, 0, + initial_args); initial_args = false; - initial_argc = cmd_argc; - initial_argv_chars = cmd_argv_chars; + bc_ctl.initial_argc = bc_state.cmd_argc; + bc_state.cmd_initial_argv_chars = bc_state.cmd_argv_chars; while ((*read_args) () != -1) - if (lines_per_exec && lineno >= lines_per_exec) + if (bc_ctl.lines_per_exec && lineno >= bc_ctl.lines_per_exec) { - do_exec (); + xargs_do_exec (&bc_ctl, &bc_state); lineno = 0; } /* SYSV xargs seems to do at least one exec, even if the input is empty. */ - if (cmd_argc != initial_argc + if (bc_state.cmd_argc != bc_ctl.initial_argc || (always_run_command && procs_executed == 0)) - do_exec (); + xargs_do_exec (&bc_ctl, &bc_state); + } else { @@ -401,23 +703,36 @@ main (argc, argv) for (i = optind; i < argc; i++) arglen[i] = strlen(argv[i]); - rplen = strlen (replace_pat); + bc_ctl.rplen = strlen (bc_ctl.replace_pat); while ((len = (*read_args) ()) != -1) { /* Don't do insert on the command name. */ - push_arg (argv[optind], arglen[optind] + 1); + bc_clear_args(&bc_ctl, &bc_state); + bc_state.cmd_argv_chars = 0; /* begin at start of buffer */ + + bc_push_arg (&bc_ctl, &bc_state, + argv[optind], arglen[optind] + 1, + NULL, 0, + initial_args); len--; + initial_args = false; + for (i = optind + 1; i < argc; i++) - do_insert (argv[i], arglen[i], len); - do_exec (); + bc_do_insert (&bc_ctl, &bc_state, + argv[i], arglen[i], + NULL, 0, + linebuf, len, + initial_args); + xargs_do_exec (&bc_ctl, &bc_state); } } - wait_for_proc (true); - exit (child_error); + original_exit_value = child_error; + return child_error; } -/* Read a line of arguments from stdin and add them to the list of + +/* Read a line of arguments from the input and add them to the list of arguments to pass to the command. Ignore blank lines and initial blanks. Single and double quotes and backslashes quote metacharacters and blanks as they do in the shell. @@ -425,7 +740,7 @@ main (argc, argv) otherwise the length of the last string read (including the null). */ static int -read_line () +read_line (void) { static boolean eof = false; /* Start out in mode SPACE to always strip leading spaces (even with -i). */ @@ -437,14 +752,14 @@ read_line () int len; char *p = linebuf; /* Including the NUL, the args must not grow past this point. */ - char *endbuf = linebuf + arg_max - initial_argv_chars - 1; + char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1; if (eof) return -1; while (1) { prevc = c; - c = getc (stdin); + c = getc (input_stream); if (c == EOF) { /* COMPAT: SYSV seems to ignore stuff on a line that @@ -454,11 +769,19 @@ read_line () return -1; *p++ = '\0'; len = p - linebuf; - /* FIXME we don't check for unterminated quotes here. */ + if (state == QUOTE) + { + exec_if_possible (); + error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"), + quotc == '"' ? _("double") : _("single")); + } if (first && EOF_STR (linebuf)) return -1; - if (!replace_pat) - push_arg (linebuf, len); + if (!bc_ctl.replace_pat) + bc_push_arg (&bc_ctl, &bc_state, + linebuf, len, + NULL, 0, + initial_args); return len; } switch (state) @@ -487,11 +810,14 @@ read_line () eof = true; return first ? -1 : len; } - if (!replace_pat) - push_arg (linebuf, len); + if (!bc_ctl.replace_pat) + bc_push_arg (&bc_ctl, &bc_state, + linebuf, len, + NULL, 0, + initial_args); return len; } - if (!replace_pat && ISSPACE (c)) + if (!bc_ctl.replace_pat && ISSPACE (c)) { *p++ = '\0'; len = p - linebuf; @@ -500,7 +826,10 @@ read_line () eof = true; return first ? -1 : len; } - push_arg (linebuf, len); + bc_push_arg (&bc_ctl, &bc_state, + linebuf, len, + NULL, 0, + initial_args); p = linebuf; state = SPACE; first = false; @@ -522,8 +851,11 @@ read_line () case QUOTE: if (c == '\n') - error (1, 0, "unmatched %s quote", - quotc == '"' ? "double" : "single"); + { + exec_if_possible (); + error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"), + quotc == '"' ? _("double") : _("single")); + } if (c == quotc) { state = NORM; @@ -535,31 +867,38 @@ read_line () state = NORM; break; } +#if 1 if (p >= endbuf) - error (1, 0, "argument line too long"); + { + exec_if_possible (); + error (1, 0, _("argument line too long")); + } *p++ = c; +#else + append_char_to_buf(&linebuf, &endbuf, &p, c); +#endif } } -/* Read a null-terminated string from stdin and add it to the list of +/* Read a null-terminated string from the input and add it to the list of arguments to pass to the command. Return -1 if eof (either physical or logical) is reached, otherwise the length of the string read (including the null). */ static int -read_string () +read_string (void) { static boolean eof = false; int len; char *p = linebuf; /* Including the NUL, the args must not grow past this point. */ - char *endbuf = linebuf + arg_max - initial_argv_chars - 1; + char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1; if (eof) return -1; while (1) { - int c = getc (stdin); + int c = getc (input_stream); if (c == EOF) { eof = true; @@ -567,149 +906,46 @@ read_string () return -1; *p++ = '\0'; len = p - linebuf; - if (!replace_pat) - push_arg (linebuf, len); + if (!bc_ctl.replace_pat) + bc_push_arg (&bc_ctl, &bc_state, + linebuf, len, + NULL, 0, + initial_args); return len; } - if (c == '\0') + if (c == input_delimiter) { lineno++; /* For -l. */ *p++ = '\0'; len = p - linebuf; - if (!replace_pat) - push_arg (linebuf, len); + if (!bc_ctl.replace_pat) + bc_push_arg (&bc_ctl, &bc_state, + linebuf, len, + NULL, 0, + initial_args); return len; } if (p >= endbuf) - error (1, 0, "argument line too long"); + { + exec_if_possible (); + error (1, 0, _("argument line too long")); + } *p++ = c; } } -/* Replace all instances of `replace_pat' in ARG with `linebuf', - and add the resulting string to the list of arguments for the command - to execute. - ARGLEN is the length of ARG, not including the null. - LBLEN is the length of `linebuf', not including the null. - - COMPAT: insertions on the SYSV version are limited to 255 chars per line, - and a max of 5 occurences of replace_pat in the initial-arguments. - Those restrictions do not exist here. */ - -static void -do_insert (arg, arglen, lblen) - char *arg; - size_t arglen; - size_t lblen; -{ - /* Temporary copy of each arg with the replace pattern replaced by the - real arg. */ - static char *insertbuf; - char *p; - int bytes_left = arg_max - 1; /* Bytes left on the command line. */ - - if (!insertbuf) - insertbuf = (char *) xmalloc (arg_max + 1); - p = insertbuf; - - do - { - size_t len; /* Length in ARG before `replace_pat'. */ - char *s = strstr (arg, replace_pat); - if (s) - len = s - arg; - else - len = arglen; - bytes_left -= len; - if (bytes_left <= 0) - break; - - strncpy (p, arg, len); - p += len; - arg += len; - - if (s) - { - bytes_left -= lblen; - if (bytes_left <= 0) - break; - strcpy (p, linebuf); - arg += rplen; - p += lblen; - } - } - while (*arg); - if (*arg) - error (1, 0, "command too long"); - *p++ = '\0'; - push_arg (insertbuf, p - insertbuf); -} - -/* Add ARG to the end of the list of arguments `cmd_argv' to pass - to the command. - LEN is the length of ARG, including the terminating null. - If this brings the list up to its maximum size, execute the command. */ - -static void -push_arg (arg, len) - char *arg; - size_t len; -{ - if (arg) - { - if (cmd_argv_chars + len > arg_max) - { - if (initial_args || cmd_argc == initial_argc) - error (1, 0, "can not fit single argument within argument list size limit"); - if (replace_pat - || (exit_if_size_exceeded && - (lines_per_exec || args_per_exec))) - error (1, 0, "argument list too long"); - do_exec (); - } - if (!initial_args && args_per_exec && - cmd_argc - initial_argc == args_per_exec) - do_exec (); - } - - if (cmd_argc >= cmd_argv_alloc) - { - if (!cmd_argv) - { - cmd_argv_alloc = 64; - cmd_argv = (char **) xmalloc (sizeof (char *) * cmd_argv_alloc); - } - else - { - cmd_argv_alloc *= 2; - cmd_argv = (char **) xrealloc (cmd_argv, - sizeof (char *) * cmd_argv_alloc); - } - } - - if (!arg) - cmd_argv[cmd_argc++] = NULL; - else - { - cmd_argv[cmd_argc++] = argbuf + cmd_argv_chars; - strcpy (argbuf + cmd_argv_chars, arg); - cmd_argv_chars += len; - } -} - /* Print the arguments of the command to execute. If ASK is nonzero, prompt the user for a response, and if the user responds affirmatively, return true; otherwise, return false. */ static boolean -print_args (ask) - boolean ask; +print_args (boolean ask) { int i; - for (i = 0; i < cmd_argc - 1; i++) - fprintf (stderr, "%s ", cmd_argv[i]); + for (i = 0; i < bc_state.cmd_argc - 1; i++) + fprintf (stderr, "%s ", bc_state.cmd_argv[i]); if (ask) { static FILE *tty_stream; @@ -735,15 +971,45 @@ print_args (ask) return false; } + +/* Close stdin and attach /dev/null to it. + * This resolves Savannah bug #3992. + */ +static void +prep_child_for_exec (void) +{ + if (!keep_stdin) + { + const char inputfile[] = "/dev/null"; + /* fprintf(stderr, "attaching stdin to /dev/null\n"); */ + + close(0); + if (open(inputfile, O_RDONLY) < 0) + { + /* This is not entirely fatal, since + * executing the child with a closed + * stdin is almost as good as executing it + * with its stdin attached to /dev/null. + */ + error (0, errno, "%s", inputfile); + } + } +} + + /* Execute the command that has been built in `cmd_argv'. This may involve waiting for processes that were previously executed. */ -static void -do_exec () +static int +xargs_do_exec (const struct buildcmd_control *ctl, struct buildcmd_state *state) { pid_t child; - push_arg ((char *) NULL, 0); /* Null terminate the arg list. */ + bc_push_arg (&bc_ctl, &bc_state, + (char *) NULL, 0, + NULL, 0, + false); /* Null terminate the arg list. */ + if (!query_before_executing || print_args (true)) { if (proc_max && procs_executing >= proc_max) @@ -757,26 +1023,38 @@ do_exec () switch (child) { case -1: - error (1, errno, "cannot fork"); + error (1, errno, _("cannot fork")); case 0: /* Child. */ - execvp (cmd_argv[0], cmd_argv); - error (0, errno, "%s", cmd_argv[0]); + prep_child_for_exec(); + execvp (bc_state.cmd_argv[0], bc_state.cmd_argv); + error (0, errno, "%s", bc_state.cmd_argv[0]); _exit (errno == ENOENT ? 127 : 126); + /*NOTREACHED*/ } add_proc (child); } - cmd_argc = initial_argc; - cmd_argv_chars = initial_argv_chars; + bc_clear_args(&bc_ctl, &bc_state); + return 1; /* Success */ +} + +/* Execute the command if possible. */ + +static void +exec_if_possible (void) +{ + if (bc_ctl.replace_pat || initial_args || + bc_state.cmd_argc == bc_ctl.initial_argc || bc_ctl.exit_if_size_exceeded) + return; + xargs_do_exec (&bc_ctl, &bc_state); } /* Add the process with id PID to the list of processes that have been executed. */ static void -add_proc (pid) - pid_t pid; +add_proc (pid_t pid) { int i; @@ -808,8 +1086,7 @@ add_proc (pid) Remove the processes that finish from the list of executing processes. */ static void -wait_for_proc (all) - boolean all; +wait_for_proc (boolean all) { while (procs_executing) { @@ -819,9 +1096,9 @@ wait_for_proc (all) { pid_t pid; - pid = wait (&status); - if (pid < 0) - error (1, errno, "error waiting for child process"); + while ((pid = wait (&status)) == (pid_t) -1) + if (errno != EINTR) + error (1, errno, _("error waiting for child process")); /* Find the entry in `pids' for the child process that exited. */ @@ -837,11 +1114,11 @@ wait_for_proc (all) if (WEXITSTATUS (status) == 126 || WEXITSTATUS (status) == 127) exit (WEXITSTATUS (status)); /* Can't find or run the command. */ if (WEXITSTATUS (status) == 255) - error (124, 0, "%s: exited with status 255; aborting", cmd_argv[0]); + error (124, 0, _("%s: exited with status 255; aborting"), bc_state.cmd_argv[0]); if (WIFSTOPPED (status)) - error (125, 0, "%s: stopped by signal %d", cmd_argv[0], WSTOPSIG (status)); + error (125, 0, _("%s: stopped by signal %d"), bc_state.cmd_argv[0], WSTOPSIG (status)); if (WIFSIGNALED (status)) - error (125, 0, "%s: terminated by signal %d", cmd_argv[0], WTERMSIG (status)); + error (125, 0, _("%s: terminated by signal %d"), bc_state.cmd_argv[0], WTERMSIG (status)); if (WEXITSTATUS (status) != 0) child_error = 123; @@ -850,17 +1127,43 @@ wait_for_proc (all) } } +/* Wait for all child processes to finish. */ + +static void +wait_for_proc_all (void) +{ + static boolean waiting = false; + + if (waiting) + return; + + waiting = true; + wait_for_proc (true); + waiting = false; + + if (original_exit_value != child_error) + { + /* wait_for_proc() changed the value of child_error(). This + * function is registered via atexit(), and so may have been + * called from exit(). We now know that the original value + * passed to exit() is no longer the exit status we require. + * The POSIX standard states that the behaviour if exit() is + * called more than once is undefined. Therefore we now have to + * exit with _exit() instead of exit(). + */ + _exit(child_error); + } + +} + /* Return the value of the number represented in STR. OPTION is the command line option to which STR is the argument. If the value does not fall within the boundaries MIN and MAX, - Print an error message mentioning OPTION and exit. */ + Print an error message mentioning OPTION. If FATAL is true, + we also exit. */ static long -parse_num (str, option, min, max) - char *str; - int option; - long min; - long max; +parse_num (char *str, int option, long int min, long int max, int fatal) { char *eptr; long val; @@ -868,51 +1171,57 @@ parse_num (str, option, min, max) val = strtol (str, &eptr, 10); if (eptr == str || *eptr) { - fprintf (stderr, "%s: invalid number for -%c option\n", + fprintf (stderr, _("%s: invalid number for -%c option\n"), program_name, option); - usage (stderr, 1); + usage (stderr); + exit(1); } else if (val < min) { - fprintf (stderr, "%s: value for -%c option must be >= %ld\n", + fprintf (stderr, _("%s: value for -%c option should be >= %ld\n"), program_name, option, min); - usage (stderr, 1); + if (fatal) + { + usage (stderr); + exit(1); + } + else + { + val = min; + } } else if (max >= 0 && val > max) { - fprintf (stderr, "%s: value for -%c option must be < %ld\n", + fprintf (stderr, _("%s: value for -%c option should be < %ld\n"), program_name, option, max); - usage (stderr, 1); + if (fatal) + { + usage (stderr); + exit(1); + } + else + { + val = max; + } } return val; } /* Return how much of ARG_MAX is used by the environment. */ -static long -env_size (envp) - char **envp; -{ - long len = 0; - - while (*envp) - len += strlen (*envp++) + 1; - - return len; -} - static void -usage (stream, status) - FILE *stream; - int status; +usage (FILE *stream) { - fprintf (stream, "\ -Usage: %s [-0prtx] [-e[eof-str]] [-i[replace-str]] [-l[max-lines]]\n\ - [-n max-args] [-s max-chars] [-P max-procs] [--null] [--eof[=eof-str]]\n\ - [--replace[=replace-str]] [--max-lines[=max-lines]] [--interactive]\n\ - [--max-chars=max-chars] [--verbose] [--exit] [--max-procs=max-procs]\n\ - [--max-args=max-args] [--no-run-if-empty] [--version] [--help]\n\ - [command [initial-arguments]]\n", + fprintf (stream, _("\ +Usage: %s [-0prtx] [--interactive] [--null] [-d|--delimiter=delim]\n\ + [-E eof-str] [-e[eof-str]] [--eof[=eof-str]]\n\ + [-L max-lines] [-l[max-lines]] [--max-lines[=max-lines]]\n\ + [-I replace-str] [-i[replace-str]] [--replace[=replace-str]]\n\ + [-n max-args] [--max-args=max-args]\n\ + [-s max-chars] [--max-chars=max-chars]\n\ + [-P max-procs] [--max-procs=max-procs] [--show-limits]\n\ + [--verbose] [--exit] [--no-run-if-empty] [--arg-file=file]\n\ + [--version] [--help] [command [initial-arguments]]\n"), program_name); - exit (status); + fputs (_("\nReport bugs to .\n"), stream); }