kmem.c revision 369186
1/* $FreeBSD: stable/11/contrib/ipfilter/lib/kmem.c 369186 2021-01-31 04:32:46Z cy $ */ 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) 34static const char sccsid[] = "@(#)kmem.c 1.4 1/12/96 (C) 1992 Darren Reed"; 35static const char rcsid[] = "@(#)$Id$"; 36#endif 37 38 39 40static kvm_t *kvm_f = NULL; 41 42 43int openkmem(kern, core) 44 char *kern, *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 55int kmemcpy(buf, pos, n) 56 register char *buf; 57 long pos; 58 register int n; 59{ 60 register int r; 61 62 if (!n) 63 return 0; 64 65 if (kvm_f == NULL) 66 if (openkmem(NULL, NULL) == -1) 67 return -1; 68 69 while ((r = kvm_read(kvm_f, pos, buf, n)) < n) 70 if (r <= 0) 71 { 72 fprintf(stderr, "pos=0x%lx ", (u_long)pos); 73 perror("kmemcpy:read"); 74 return -1; 75 } 76 else 77 { 78 buf += r; 79 pos += r; 80 n -= r; 81 } 82 return 0; 83} 84 85int kstrncpy(buf, pos, n) 86 register char *buf; 87 long pos; 88 register int n; 89{ 90 register int r; 91 92 if (!n) 93 return 0; 94 95 if (kvm_f == NULL) 96 if (openkmem(NULL, NULL) == -1) 97 return -1; 98 99 while (n > 0) 100 { 101 r = kvm_read(kvm_f, pos, buf, 1); 102 if (r <= 0) 103 { 104 fprintf(stderr, "pos=0x%lx ", (u_long)pos); 105 perror("kmemcpy:read"); 106 return -1; 107 } 108 else 109 { 110 if (*buf == '\0') 111 break; 112 buf++; 113 pos++; 114 n--; 115 } 116 } 117 return 0; 118} 119