xref: /dragonfly/usr.bin/gcore/gcore.c (revision 23265324)
1 /*-
2  * Copyright (c) 1992, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1992, 1993 The Regents of the University of California.  All rights reserved.
34  * @(#)gcore.c	8.2 (Berkeley) 9/23/93
35  * $FreeBSD: src/usr.bin/gcore/gcore.c,v 1.15.2.2 2001/08/17 20:56:22 mikeh Exp $
36  * $DragonFly: src/usr.bin/gcore/gcore.c,v 1.10 2007/02/18 16:15:24 corecode Exp $
37  */
38 
39 /*
40  * Originally written by Eric Cooper in Fall 1981.
41  * Inspired by a version 6 program by Len Levin, 1978.
42  * Several pieces of code lifted from Bill Joy's 4BSD ps.
43  * Most recently, hacked beyond recognition for 4.4BSD by Steven McCanne,
44  * Lawrence Berkeley Laboratory.
45  *
46  * Portions of this software were developed by the Computer Systems
47  * Engineering group at Lawrence Berkeley Laboratory under DARPA
48  * contract BG 91-66 and contributed to Berkeley.
49  */
50 #include <sys/param.h>
51 #include <sys/time.h>
52 #include <sys/stat.h>
53 #include <sys/user.h>
54 #include <sys/sysctl.h>
55 #include <machine/elf.h>
56 
57 #include <machine/vmparam.h>
58 
59 #include <a.out.h>
60 #include <err.h>
61 #include <fcntl.h>
62 #include <kvm.h>
63 #include <limits.h>
64 #include <signal.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <unistd.h>
69 
70 #include "extern.h"
71 
72 static void	core(int, int, struct kinfo_proc *);
73 static void	datadump(int, int, pid_t, u_long, int);
74 static void	killed(int);
75 static void	restart_target(void);
76 static void	usage(void) __dead2;
77 static void	userdump(int, pid_t, u_long, int);
78 
79 kvm_t *kd;
80 
81 static int data_offset;
82 static pid_t pid;
83 
84 int
85 main(int argc, char **argv)
86 {
87 	struct kinfo_proc *ki = NULL;
88 	struct exec exec;
89 	int ch, cnt, efd, fd, sflag, uid;
90 	char *binfile, *corefile;
91 	char errbuf[_POSIX2_LINE_MAX], fname[MAXPATHLEN + 1];
92 	int is_aout;
93 
94 	sflag = 0;
95 	corefile = NULL;
96         while ((ch = getopt(argc, argv, "c:s")) != -1) {
97                 switch (ch) {
98                 case 'c':
99 			corefile = optarg;
100                         break;
101 		case 's':
102 			sflag = 1;
103 			break;
104 		default:
105 			usage();
106 			break;
107 		}
108 	}
109 	argv += optind;
110 	argc -= optind;
111 
112 	/* XXX we should check that the pid argument is really a number */
113 	switch (argc) {
114 	case 1:
115 		pid = atoi(argv[0]);
116 		asprintf(&binfile, "/proc/%d/file", pid);
117 		if (binfile == NULL)
118 			errx(1, "allocation failure");
119 		break;
120 	case 2:
121 		pid = atoi(argv[1]);
122 		binfile = argv[0];
123 		break;
124 	default:
125 		usage();
126 	}
127 
128 	efd = open(binfile, O_RDONLY, 0);
129 	if (efd < 0)
130 		err(1, "%s", binfile);
131 
132 	cnt = read(efd, &exec, sizeof(exec));
133 	if (cnt != sizeof(exec))
134 		errx(1, "%s exec header: %s",
135 		    binfile, cnt > 0 ? strerror(EIO) : strerror(errno));
136 	if (!N_BADMAG(exec)) {
137 		is_aout = 1;
138 		/*
139 		 * This legacy a.out support uses the kvm interface instead
140 		 * of procfs.
141 		 */
142 		kd = kvm_openfiles(0, 0, 0, O_RDONLY, errbuf);
143 		if (kd == NULL)
144 			errx(1, "%s", errbuf);
145 
146 		uid = getuid();
147 
148 		ki = kvm_getprocs(kd, KERN_PROC_PID, pid, &cnt);
149 		if (ki == NULL || cnt != 1)
150 			errx(1, "%d: not found", pid);
151 
152 		if (ki->kp_ruid != uid && uid != 0)
153 			errx(1, "%d: not owner", pid);
154 
155 		if (ki->kp_stat == SZOMB)
156 			errx(1, "%d: zombie", pid);
157 
158 		if (ki->kp_flags & P_WEXIT)
159 			errx(1, "%d: process exiting", pid);
160 		if (ki->kp_flags & P_SYSTEM)	/* Swapper or pagedaemon. */
161 			errx(1, "%d: system process", pid);
162 		if (exec.a_text != ptoa(ki->kp_vm_tsize))
163 			errx(1, "The executable %s does not belong to"
164 			    " process %d!\n"
165 			    "Text segment size (in bytes): executable %ld,"
166 			    " process %d", binfile, pid, exec.a_text,
167 			     ptoa(ki->kp_vm_tsize));
168 		data_offset = N_DATOFF(exec);
169 	} else if (IS_ELF(*(Elf_Ehdr *)&exec)) {
170 		is_aout = 0;
171 		close(efd);
172 	} else
173 		errx(1, "Invalid executable file");
174 
175 	if (corefile == NULL) {
176 		(void)snprintf(fname, sizeof(fname), "core.%d", pid);
177 		corefile = fname;
178 	}
179 	fd = open(corefile, O_RDWR|O_CREAT|O_TRUNC, DEFFILEMODE);
180 	if (fd < 0)
181 		err(1, "%s", corefile);
182 
183 	if (sflag) {
184 		signal(SIGHUP, killed);
185 		signal(SIGINT, killed);
186 		signal(SIGTERM, killed);
187 		if (kill(pid, SIGSTOP) == -1)
188 			err(1, "%d: stop signal", pid);
189 		atexit(restart_target);
190 	}
191 
192 	if (is_aout)
193 		core(efd, fd, ki);
194 	else
195 		elf_coredump(fd, pid);
196 
197 	(void)close(fd);
198 	exit(0);
199 }
200 
201 /*
202  * core --
203  *	Build the core file.
204  */
205 void
206 core(int efd, int fd, struct kinfo_proc *ki)
207 {
208 	union {
209 		struct user user;
210 		char ubytes[ctob(UPAGES)];
211 	} uarea;
212 	int tsize = ki->kp_vm_tsize;
213 	int dsize = ki->kp_vm_dsize;
214 	int ssize = ki->kp_vm_ssize;
215 	int cnt;
216 
217 	/* Read in user struct */
218 	cnt = kvm_read(kd, ki->kp_pid, &uarea, sizeof(uarea));
219 	if (cnt != sizeof(uarea))
220 		errx(1, "read user structure: %s",
221 		    cnt > 0 ? strerror(EIO) : strerror(errno));
222 
223 	/*
224 	 * Fill in the eproc vm parameters, since these are garbage unless
225 	 * the kernel is dumping core or something.
226 	 */
227 	uarea.user.u_kproc = *ki;
228 
229 	/* Dump user area */
230 	cnt = write(fd, &uarea, sizeof(uarea));
231 	if (cnt != sizeof(uarea))
232 		errx(1, "write user structure: %s",
233 		    cnt > 0 ? strerror(EIO) : strerror(errno));
234 
235 	/* Dump data segment */
236 	datadump(efd, fd, ki->kp_pid, USRTEXT + ctob(tsize), dsize);
237 
238 	/* Dump stack segment */
239 	userdump(fd, ki->kp_pid, USRSTACK - ctob(ssize), ssize);
240 
241 	/* Dump machine dependent portions of the core. */
242 	md_core(kd, fd, ki);
243 }
244 
245 void
246 datadump(int efd, int fd, pid_t pid,
247          u_long addr, int npage)
248 {
249 	int cc, delta;
250 	char buffer[PAGE_SIZE];
251 
252 	delta = data_offset - addr;
253 	while (--npage >= 0) {
254 		cc = kvm_uread(kd, pid, addr, buffer, PAGE_SIZE);
255 		if (cc != PAGE_SIZE) {
256 			/* Try to read the page from the executable. */
257 			if (lseek(efd, (off_t)addr + delta, SEEK_SET) == -1)
258 				err(1, "seek executable: %s", strerror(errno));
259 			cc = read(efd, buffer, sizeof(buffer));
260 			if (cc != sizeof(buffer)) {
261 				if (cc < 0)
262 					err(1, "read executable");
263 				else	/* Assume untouched bss page. */
264 					bzero(buffer, sizeof(buffer));
265 			}
266 		}
267 		cc = write(fd, buffer, PAGE_SIZE);
268 		if (cc != PAGE_SIZE)
269 			errx(1, "write data segment: %s",
270 			    cc > 0 ? strerror(EIO) : strerror(errno));
271 		addr += PAGE_SIZE;
272 	}
273 }
274 
275 static void
276 killed(int sig)
277 {
278 	restart_target();
279 	signal(sig, SIG_DFL);
280 	kill(getpid(), sig);
281 }
282 
283 static void
284 restart_target(void)
285 {
286 	kill(pid, SIGCONT);
287 }
288 
289 void
290 userdump(int fd, pid_t pid, u_long addr,
291          int npage)
292 {
293 	int cc;
294 	char buffer[PAGE_SIZE];
295 
296 	while (--npage >= 0) {
297 		cc = kvm_uread(kd, pid, addr, buffer, PAGE_SIZE);
298 		if (cc != PAGE_SIZE)
299 			/* Could be an untouched fill-with-zero page. */
300 			bzero(buffer, PAGE_SIZE);
301 		cc = write(fd, buffer, PAGE_SIZE);
302 		if (cc != PAGE_SIZE)
303 			errx(1, "write stack segment: %s",
304 			    cc > 0 ? strerror(EIO) : strerror(errno));
305 		addr += PAGE_SIZE;
306 	}
307 }
308 
309 void
310 usage(void)
311 {
312 	(void)fprintf(stderr, "usage: gcore [-s] [-c core] [executable] pid\n");
313 	exit(1);
314 }
315