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