9a326c60da7f47db10c0a177938a2cc3897c29b5
[external/binutils.git] / gdb / testsuite / gdb.base / coredump-filter.c
1 /* Copyright 2015-2016 Free Software Foundation, Inc.
2
3    This file is part of GDB.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 #define _GNU_SOURCE
19 #include <stdlib.h>
20 #include <assert.h>
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <sys/mman.h>
24 #include <errno.h>
25 #include <string.h>
26
27 static void *
28 do_mmap (void *addr, size_t size, int prot, int flags, int fd, off_t offset)
29 {
30   void *ret = mmap (addr, size, prot, flags, fd, offset);
31
32   assert (ret != NULL);
33   return ret;
34 }
35
36 int
37 main (int argc, char *argv[])
38 {
39   const size_t size = 10;
40   const int default_prot = PROT_READ | PROT_WRITE;
41   char *private_anon, *shared_anon;
42   char *dont_dump;
43   int i;
44
45   private_anon = do_mmap (NULL, size, default_prot,
46                           MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
47   memset (private_anon, 0x11, size);
48
49   shared_anon = do_mmap (NULL, size, default_prot,
50                          MAP_SHARED | MAP_ANONYMOUS, -1, 0);
51   memset (shared_anon, 0x22, size);
52
53   dont_dump = do_mmap (NULL, size, default_prot,
54                        MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
55   memset (dont_dump, 0x55, size);
56   i = madvise (dont_dump, size, MADV_DONTDUMP);
57   assert_perror (errno);
58   assert (i == 0);
59
60   return 0; /* break-here */
61 }
62
63 /* Write V to /proc/self/coredump_filter.  Return 0 on success.  */
64
65 int
66 set_coredump_filter (int v)
67 {
68   FILE *f = fopen("/proc/self/coredump_filter", "r+");
69
70   if (f == NULL)
71     return 1;
72
73   fprintf(f, "%#x", v);
74
75   fclose (f);
76   return 0;
77 }