xref: /freebsd/sbin/ipf/libipf/kmem.c (revision edf8578117e8844e02c0121147f45e4609b30680)
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 #if !defined(lint)
33 static const char sccsid[] = "@(#)kmem.c	1.4 1/12/96 (C) 1992 Darren Reed";
34 static const char rcsid[] = "@(#)$Id$";
35 #endif
36 
37 
38 
39 static	kvm_t	*kvm_f = NULL;
40 
41 
42 int
43 openkmem(char *kern, char *core)
44 {
45 	kvm_f = kvm_open(kern, core, NULL, O_RDONLY, NULL);
46 	if (kvm_f == NULL)
47 	    {
48 		perror("openkmem:open");
49 		return (-1);
50 	    }
51 	return (kvm_f != NULL);
52 }
53 
54 int
55 kmemcpy(register char *buf, long pos, register int n)
56 {
57 	register int	r;
58 
59 	if (!n)
60 		return (0);
61 
62 	if (kvm_f == NULL)
63 		if (openkmem(NULL, NULL) == -1)
64 			return (-1);
65 
66 	while ((r = kvm_read(kvm_f, pos, buf, n)) < n)
67 		if (r <= 0)
68 		    {
69 			fprintf(stderr, "pos=0x%lx ", (u_long)pos);
70 			perror("kmemcpy:read");
71 			return (-1);
72 		    }
73 		else
74 		    {
75 			buf += r;
76 			pos += r;
77 			n -= r;
78 		    }
79 	return (0);
80 }
81 
82 int
83 kstrncpy(register char *buf, long pos, register int n)
84 {
85 	register int	r;
86 
87 	if (!n)
88 		return (0);
89 
90 	if (kvm_f == NULL)
91 		if (openkmem(NULL, NULL) == -1)
92 			return (-1);
93 
94 	while (n > 0)
95 	    {
96 		r = kvm_read(kvm_f, pos, buf, 1);
97 		if (r <= 0)
98 		    {
99 			fprintf(stderr, "pos=0x%lx ", (u_long)pos);
100 			perror("kmemcpy:read");
101 			return (-1);
102 		    }
103 		else
104 		    {
105 			if (*buf == '\0')
106 				break;
107 			buf++;
108 			pos++;
109 			n--;
110 		    }
111 	    }
112 	return (0);
113 }
114