Updated to fedora-glibc-20041215T2056
[glibc.git] / sysdeps / unix / sysv / linux / readonly-area.c
blob3db90023bf6b7f59c12448462aa2b2400057886c
1 /* Copyright (C) 2004 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, write to the Free
16 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
17 02111-1307 USA. */
19 #include <stdint.h>
20 #include <stdio.h>
21 #include <stdio_ext.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include "libio/libioP.h"
26 /* Return 1 if the whole area PTR .. PTR+SIZE is not writable.
27 Return -1 if it is writable. */
29 int
30 __readonly_area (const char *ptr, size_t size)
32 const void *ptr_end = ptr + size;
34 FILE *fp = fopen ("/proc/self/maps", "rc");
35 if (fp == NULL)
36 /* We don't know. Returning 1 here means that programs using %n
37 and -D_FORTIFY_SOURCE=2 will work even when /proc is not mounted,
38 but will allow %n even in writable areas. */
39 return 1;
41 /* We need no locking. */
42 __fsetlocking (fp, FSETLOCKING_BYCALLER);
44 char *line = NULL;
45 size_t linelen = 0;
47 while (! feof_unlocked (fp))
49 if (_IO_getdelim (&line, &linelen, '\n', fp) <= 0)
50 break;
52 char *p;
53 uintptr_t from = strtoul (line, &p, 16);
55 if (p == line || *p++ != '-')
56 break;
58 char *q;
59 uintptr_t to = strtoul (p, &q, 16);
61 if (q == p || *q++ != ' ')
62 break;
64 if (from < (uintptr_t) ptr_end && to > (uintptr_t) ptr)
66 /* Found an entry that at least partially covers the area. */
67 if (*q++ != 'r' || *q++ != '-')
68 break;
70 if (from <= (uintptr_t) ptr && to >= (uintptr_t) ptr_end)
72 size = 0;
73 break;
75 else if (from <= (uintptr_t) ptr)
76 size -= to - (uintptr_t) ptr;
77 else if (to >= (uintptr_t) ptr_end)
78 size -= (uintptr_t) ptr_end - from;
79 else
80 size -= to - from;
82 if (!size)
83 break;
87 fclose (fp);
88 free (line);
90 /* If the whole area between ptr and ptr_end is covered by read-only
91 VMAs, return 1. Otherwise return -1. */
92 return size == 0 ? 1 : -1;