1
2 /*
3 * Copyright (C) 2012 by Darren Reed.
4 *
5 * See the IPFILTER.LICENCE file for details on licencing.
6 */
7 /*
8 * kmemcpy() - copies n bytes from kernel memory into user buffer.
9 * returns 0 on success, -1 on error.
10 */
11
12 #include <stdio.h>
13 #include <sys/param.h>
14 #include <sys/types.h>
15 #include <sys/uio.h>
16 #include <unistd.h>
17 #include <string.h>
18 #include <fcntl.h>
19 #include <sys/file.h>
20 #include <kvm.h>
21 #include <fcntl.h>
22 #include <sys/socket.h>
23 #include <sys/ioctl.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <netinet/in_systm.h>
27 #include <netinet/ip.h>
28 #include <net/if.h>
29
30 #include "kmem.h"
31
32
33
34
35 static kvm_t *kvm_f = NULL;
36
37
38 int
openkmem(char * kern,char * core)39 openkmem(char *kern, char *core)
40 {
41 kvm_f = kvm_open(kern, core, NULL, O_RDONLY, NULL);
42 if (kvm_f == NULL)
43 {
44 perror("openkmem:open");
45 return (-1);
46 }
47 return (kvm_f != NULL);
48 }
49
50 int
kmemcpy(register char * buf,long pos,register int n)51 kmemcpy(register char *buf, long pos, register int n)
52 {
53 register int r;
54
55 if (!n)
56 return (0);
57
58 if (kvm_f == NULL)
59 if (openkmem(NULL, NULL) == -1)
60 return (-1);
61
62 while ((r = kvm_read(kvm_f, pos, buf, n)) < n)
63 if (r <= 0)
64 {
65 fprintf(stderr, "pos=0x%lx ", (u_long)pos);
66 perror("kmemcpy:read");
67 return (-1);
68 }
69 else
70 {
71 buf += r;
72 pos += r;
73 n -= r;
74 }
75 return (0);
76 }
77
78 int
kstrncpy(register char * buf,long pos,register int n)79 kstrncpy(register char *buf, long pos, register int n)
80 {
81 register int r;
82
83 if (!n)
84 return (0);
85
86 if (kvm_f == NULL)
87 if (openkmem(NULL, NULL) == -1)
88 return (-1);
89
90 while (n > 0)
91 {
92 r = kvm_read(kvm_f, pos, buf, 1);
93 if (r <= 0)
94 {
95 fprintf(stderr, "pos=0x%lx ", (u_long)pos);
96 perror("kmemcpy:read");
97 return (-1);
98 }
99 else
100 {
101 if (*buf == '\0')
102 break;
103 buf++;
104 pos++;
105 n--;
106 }
107 }
108 return (0);
109 }
110