xref: /dflybsd-src/usr.bin/gcore/gcore.c (revision 3412cacb5a88ff95d06808eeed783b8499b5256e)
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.5 2003/11/03 19:31:29 eirikn 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/proc.h>
54 #include <sys/user.h>
55 #include <sys/sysctl.h>
56 #include <machine/elf.h>
57 
58 #include <machine/vmparam.h>
59 
60 #include <a.out.h>
61 #include <err.h>
62 #include <fcntl.h>
63 #include <kvm.h>
64 #include <limits.h>
65 #include <signal.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <unistd.h>
70 
71 #include "extern.h"
72 
73 static void	core(int, int, struct kinfo_proc *);
74 static void	datadump(int, int, struct proc *, u_long, int);
75 static void	killed(int);
76 static void	restart_target(void);
77 static void	usage(void) __dead2;
78 static void	userdump(int, struct proc *, u_long, int);
79 
80 kvm_t *kd;
81 /* XXX undocumented routine, should be in kvm.h? */
82 ssize_t kvm_uread(kvm_t *, const struct proc *, u_long, char *, size_t);
83 
84 static int data_offset;
85 static pid_t pid;
86 
87 int
88 main(int argc, char **argv)
89 {
90 	register struct proc *p;
91 	struct kinfo_proc *ki = NULL;
92 	struct exec exec;
93 	int ch, cnt, efd, fd, sflag, uid;
94 	char *binfile, *corefile;
95 	char errbuf[_POSIX2_LINE_MAX], fname[MAXPATHLEN + 1];
96 	int is_aout;
97 
98 	sflag = 0;
99 	corefile = NULL;
100         while ((ch = getopt(argc, argv, "c:s")) != -1) {
101                 switch (ch) {
102                 case 'c':
103 			corefile = optarg;
104                         break;
105 		case 's':
106 			sflag = 1;
107 			break;
108 		default:
109 			usage();
110 			break;
111 		}
112 	}
113 	argv += optind;
114 	argc -= optind;
115 
116 	/* XXX we should check that the pid argument is really a number */
117 	switch (argc) {
118 	case 1:
119 		pid = atoi(argv[0]);
120 		asprintf(&binfile, "/proc/%d/file", pid);
121 		if (binfile == NULL)
122 			errx(1, "allocation failure");
123 		break;
124 	case 2:
125 		pid = atoi(argv[1]);
126 		binfile = argv[0];
127 		break;
128 	default:
129 		usage();
130 	}
131 
132 	efd = open(binfile, O_RDONLY, 0);
133 	if (efd < 0)
134 		err(1, "%s", binfile);
135 
136 	cnt = read(efd, &exec, sizeof(exec));
137 	if (cnt != sizeof(exec))
138 		errx(1, "%s exec header: %s",
139 		    binfile, cnt > 0 ? strerror(EIO) : strerror(errno));
140 	if (!N_BADMAG(exec)) {
141 		is_aout = 1;
142 		/*
143 		 * This legacy a.out support uses the kvm interface instead
144 		 * of procfs.
145 		 */
146 		kd = kvm_openfiles(0, 0, 0, O_RDONLY, errbuf);
147 		if (kd == NULL)
148 			errx(1, "%s", errbuf);
149 
150 		uid = getuid();
151 
152 		ki = kvm_getprocs(kd, KERN_PROC_PID, pid, &cnt);
153 		if (ki == NULL || cnt != 1)
154 			errx(1, "%d: not found", pid);
155 
156 		p = &ki->kp_proc;
157 		if (ki->kp_eproc.e_ucred.cr_ruid != uid && uid != 0)
158 			errx(1, "%d: not owner", pid);
159 
160 		if (p->p_stat == SZOMB)
161 			errx(1, "%d: zombie", pid);
162 
163 		if (p->p_flag & P_WEXIT)
164 			errx(1, "%d: process exiting", pid);
165 		if (p->p_flag & P_SYSTEM)	/* Swapper or pagedaemon. */
166 			errx(1, "%d: system process", pid);
167 		if (exec.a_text != ptoa(ki->kp_eproc.e_vm.vm_tsize))
168 			errx(1, "The executable %s does not belong to"
169 			    " process %d!\n"
170 			    "Text segment size (in bytes): executable %ld,"
171 			    " process %d", binfile, pid, exec.a_text,
172 			     ptoa(ki->kp_eproc.e_vm.vm_tsize));
173 		data_offset = N_DATOFF(exec);
174 	} else if (IS_ELF(*(Elf_Ehdr *)&exec)) {
175 		is_aout = 0;
176 		close(efd);
177 	} else
178 		errx(1, "Invalid executable file");
179 
180 	if (corefile == NULL) {
181 		(void)snprintf(fname, sizeof(fname), "core.%d", pid);
182 		corefile = fname;
183 	}
184 	fd = open(corefile, O_RDWR|O_CREAT|O_TRUNC, DEFFILEMODE);
185 	if (fd < 0)
186 		err(1, "%s", corefile);
187 
188 	if (sflag) {
189 		signal(SIGHUP, killed);
190 		signal(SIGINT, killed);
191 		signal(SIGTERM, killed);
192 		if (kill(pid, SIGSTOP) == -1)
193 			err(1, "%d: stop signal", pid);
194 		atexit(restart_target);
195 	}
196 
197 	if (is_aout)
198 		core(efd, fd, ki);
199 	else
200 		elf_coredump(fd, pid);
201 
202 	(void)close(fd);
203 	exit(0);
204 }
205 
206 /*
207  * core --
208  *	Build the core file.
209  */
210 void
211 core(int efd, int fd, struct kinfo_proc *ki)
212 {
213 	union {
214 		struct user user;
215 		char ubytes[ctob(UPAGES)];
216 	} uarea;
217 	struct proc *p = &ki->kp_proc;
218 	int tsize = ki->kp_eproc.e_vm.vm_tsize;
219 	int dsize = ki->kp_eproc.e_vm.vm_dsize;
220 	int ssize = ki->kp_eproc.e_vm.vm_ssize;
221 	int cnt;
222 
223 	/* Read in user struct */
224 	cnt = kvm_read(kd, (u_long)p->p_addr, &uarea, sizeof(uarea));
225 	if (cnt != sizeof(uarea))
226 		errx(1, "read user structure: %s",
227 		    cnt > 0 ? strerror(EIO) : strerror(errno));
228 
229 	/*
230 	 * Fill in the eproc vm parameters, since these are garbage unless
231 	 * the kernel is dumping core or something.
232 	 */
233 	uarea.user.u_kproc = *ki;
234 
235 	/* Dump user area */
236 	cnt = write(fd, &uarea, sizeof(uarea));
237 	if (cnt != sizeof(uarea))
238 		errx(1, "write user structure: %s",
239 		    cnt > 0 ? strerror(EIO) : strerror(errno));
240 
241 	/* Dump data segment */
242 	datadump(efd, fd, p, USRTEXT + ctob(tsize), dsize);
243 
244 	/* Dump stack segment */
245 	userdump(fd, p, USRSTACK - ctob(ssize), ssize);
246 
247 	/* Dump machine dependent portions of the core. */
248 	md_core(kd, fd, ki);
249 }
250 
251 void
252 datadump(register int efd, register int fd, struct proc *p,
253          register u_long addr, register int npage)
254 {
255 	register int cc, delta;
256 	char buffer[PAGE_SIZE];
257 
258 	delta = data_offset - addr;
259 	while (--npage >= 0) {
260 		cc = kvm_uread(kd, p, addr, buffer, PAGE_SIZE);
261 		if (cc != PAGE_SIZE) {
262 			/* Try to read the page from the executable. */
263 			if (lseek(efd, (off_t)addr + delta, SEEK_SET) == -1)
264 				err(1, "seek executable: %s", strerror(errno));
265 			cc = read(efd, buffer, sizeof(buffer));
266 			if (cc != sizeof(buffer)) {
267 				if (cc < 0)
268 					err(1, "read executable");
269 				else	/* Assume untouched bss page. */
270 					bzero(buffer, sizeof(buffer));
271 			}
272 		}
273 		cc = write(fd, buffer, PAGE_SIZE);
274 		if (cc != PAGE_SIZE)
275 			errx(1, "write data segment: %s",
276 			    cc > 0 ? strerror(EIO) : strerror(errno));
277 		addr += PAGE_SIZE;
278 	}
279 }
280 
281 static void
282 killed(int sig)
283 {
284 	restart_target();
285 	signal(sig, SIG_DFL);
286 	kill(getpid(), sig);
287 }
288 
289 static void
290 restart_target(void)
291 {
292 	kill(pid, SIGCONT);
293 }
294 
295 void
296 userdump(register int fd, struct proc *p, register u_long addr,
297          register int npage)
298 {
299 	register int cc;
300 	char buffer[PAGE_SIZE];
301 
302 	while (--npage >= 0) {
303 		cc = kvm_uread(kd, p, addr, buffer, PAGE_SIZE);
304 		if (cc != PAGE_SIZE)
305 			/* Could be an untouched fill-with-zero page. */
306 			bzero(buffer, PAGE_SIZE);
307 		cc = write(fd, buffer, PAGE_SIZE);
308 		if (cc != PAGE_SIZE)
309 			errx(1, "write stack segment: %s",
310 			    cc > 0 ? strerror(EIO) : strerror(errno));
311 		addr += PAGE_SIZE;
312 	}
313 }
314 
315 void
316 usage(void)
317 {
318 	(void)fprintf(stderr, "usage: gcore [-s] [-c core] [executable] pid\n");
319 	exit(1);
320 }
321