bcfe869c505892f391a21ee39a3358dcbeec140d
[pspp] / m4 / memchr.m4
1 # memchr.m4 serial 6
2 dnl Copyright (C) 2002, 2003, 2004, 2009 Free Software Foundation, Inc.
3 dnl This file is free software; the Free Software Foundation
4 dnl gives unlimited permission to copy and/or distribute it,
5 dnl with or without modifications, as long as this notice is preserved.
6
7 AC_DEFUN([gl_FUNC_MEMCHR],
8 [
9   dnl Check for prerequisites for memory fence checks.
10   gl_FUNC_MMAP_ANON
11   AC_CHECK_HEADERS_ONCE([sys/mman.h])
12   AC_CHECK_FUNCS_ONCE([mprotect])
13
14   dnl These days, we assume memchr is present.  But just in case...
15   AC_REQUIRE([gl_HEADER_STRING_H_DEFAULTS])
16   AC_REPLACE_FUNCS([memchr])
17   if test $ac_cv_func_memchr = no; then
18     gl_PREREQ_MEMCHR
19     REPLACE_MEMCHR=1
20   fi
21
22   if test $ac_cv_func_memchr = yes; then
23     # Detect platform-specific bugs in some versions of glibc:
24     # memchr should not dereference anything with length 0
25     #   http://bugzilla.redhat.com/499689
26     # memchr should not dereference overestimated length after a match
27     #   http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=521737
28     # Assume that memchr works on platforms that lack mprotect.
29     AC_CACHE_CHECK([whether memchr works], [gl_cv_func_memchr_works],
30       [AC_RUN_IFELSE([AC_LANG_PROGRAM([[
31 #include <string.h>
32 #if HAVE_SYS_MMAN_H
33 # include <fcntl.h>
34 # include <unistd.h>
35 # include <sys/types.h>
36 # include <sys/mman.h>
37 # ifndef MAP_FILE
38 #  define MAP_FILE 0
39 # endif
40 #endif
41 ]], [[
42   char *fence = NULL;
43 #if HAVE_SYS_MMAN_H && HAVE_MPROTECT
44 # if HAVE_MAP_ANONYMOUS
45   const int flags = MAP_ANONYMOUS | MAP_PRIVATE;
46   const int fd = -1;
47 # else /* !HAVE_MAP_ANONYMOUS */
48   const int flags = MAP_FILE | MAP_PRIVATE;
49   int fd = open ("/dev/zero", O_RDONLY, 0666);
50   if (fd >= 0)
51 # endif
52     {
53       int pagesize = getpagesize ();
54       char *two_pages =
55         (char *) mmap (NULL, 2 * pagesize, PROT_READ | PROT_WRITE,
56                        flags, fd, 0);
57       if (two_pages != (char *)(-1)
58           && mprotect (two_pages + pagesize, pagesize, PROT_NONE) == 0)
59         fence = two_pages + pagesize;
60     }
61 #endif
62   if (fence)
63     {
64       if (memchr (fence, 0, 0))
65         return 1;
66       strcpy (fence - 9, "12345678");
67       if (memchr (fence - 9, 0, 79) != fence - 1)
68         return 2;
69     }
70   return 0;
71 ]])], [gl_cv_func_memchr_works=yes], [gl_cv_func_memchr_works=no],
72       [dnl Be pessimistic for now.
73        gl_cv_func_memchr_works="guessing no"])])
74     if test "$gl_cv_func_memchr_works" != yes; then
75       gl_PREREQ_MEMCHR
76       REPLACE_MEMCHR=1
77       AC_LIBOBJ([memchr])
78     fi
79   fi
80 ])
81
82 # Prerequisites of lib/memchr.c.
83 AC_DEFUN([gl_PREREQ_MEMCHR], [
84   AC_CHECK_HEADERS([bp-sym.h])
85 ])