initial commit
[glibc.git] / sysdeps / unix / bsd / bsd4.4 / kfreebsd / readonly-area.c
1 /* Copyright (C) 2004, 2005, 2009 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3
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.
8
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.
13
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. */
18
19 #include <errno.h>
20 #include <stdint.h>
21 #include <stdio.h>
22 #include <stdio_ext.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <sys/sysctl.h>
27 #include <sys/user.h>
28 #include "libio/libioP.h"
29
30 /* Return 1 if the whole area PTR .. PTR+SIZE is not writable.
31 Return -1 if it is writable. */
32
33 int
34 __readonly_area (const char *ptr, size_t size)
35 {
36 const void *ptr_end = ptr + size;
37
38 int mib[4];
39 size_t kve_len = 0;
40 char *kve_buf, *kve_bufp;
41
42 mib[0] = CTL_KERN;
43 mib[1] = KERN_PROC;
44 mib[2] = KERN_PROC_VMMAP;
45 mib[3] = __getpid ();
46
47 if (__sysctl (mib, 4, NULL, &kve_len, NULL, 0) != 0)
48 {
49 __set_errno (ENOSYS);
50 return 1;
51 }
52
53 kve_buf = alloca (kve_len);
54 if (__sysctl (mib, 4, kve_buf, &kve_len, NULL, 0) != 0)
55 {
56 __set_errno (ENOSYS);
57 return 1;
58 }
59
60 kve_bufp = kve_buf;
61 while (kve_bufp < kve_buf + kve_len)
62 {
63 struct kinfo_vmentry *kve = (struct kinfo_vmentry *) (uintptr_t) kve_bufp;
64 kve_bufp += kve->kve_structsize;
65
66 uintptr_t from = kve->kve_start;
67 uintptr_t to = kve->kve_end;
68
69 if (from < (uintptr_t) ptr_end && to > (uintptr_t) ptr)
70 {
71 /* Found an entry that at least partially covers the area. */
72 if (!(kve->kve_protection & KVME_PROT_READ)
73 || (kve->kve_protection & KVME_PROT_WRITE))
74 break;
75
76 if (from <= (uintptr_t) ptr && to >= (uintptr_t) ptr_end)
77 {
78 size = 0;
79 break;
80 }
81 else if (from <= (uintptr_t) ptr)
82 size -= to - (uintptr_t) ptr;
83 else if (to >= (uintptr_t) ptr_end)
84 size -= (uintptr_t) ptr_end - from;
85 else
86 size -= to - from;
87
88 if (!size)
89 break;
90 }
91 }
92
93 /* If the whole area between ptr and ptr_end is covered by read-only
94 VMAs, return 1. Otherwise return -1. */
95 return size == 0 ? 1 : -1;
96 }