xref: /freebsd/usr.bin/gcore/gcore.c (revision 3ff369fed2a08f32dda232c10470b949bef9489f)
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 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1992, 1993\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)gcore.c	8.2 (Berkeley) 9/23/93";
43 #endif
44 #endif /* not lint */
45 
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 /*
50  * Originally written by Eric Cooper in Fall 1981.
51  * Inspired by a version 6 program by Len Levin, 1978.
52  * Several pieces of code lifted from Bill Joy's 4BSD ps.
53  * Most recently, hacked beyond recognition for 4.4BSD by Steven McCanne,
54  * Lawrence Berkeley Laboratory.
55  *
56  * Portions of this software were developed by the Computer Systems
57  * Engineering group at Lawrence Berkeley Laboratory under DARPA
58  * contract BG 91-66 and contributed to Berkeley.
59  */
60 
61 #include <sys/param.h>
62 #include <sys/time.h>
63 #include <sys/stat.h>
64 #include <sys/proc.h>
65 #include <sys/user.h>
66 #include <sys/sysctl.h>
67 
68 #include <machine/elf.h>
69 #include <machine/vmparam.h>
70 
71 #include <a.out.h>
72 #include <err.h>
73 #include <fcntl.h>
74 #include <kvm.h>
75 #include <limits.h>
76 #include <signal.h>
77 #include <stdio.h>
78 #include <stdlib.h>
79 #include <string.h>
80 #include <unistd.h>
81 
82 #include "extern.h"
83 
84 static void	core(int, int, struct kinfo_proc *);
85 static void	datadump(int, int, struct kinfo_proc *, u_long, int);
86 static void	killed(int);
87 static void	restart_target(void);
88 static void	usage(void) __dead2;
89 static void	userdump(int, struct kinfo_proc *, u_long, int);
90 
91 kvm_t *kd;
92 
93 static int data_offset;
94 static pid_t pid;
95 
96 int
97 main(argc, argv)
98 	int argc;
99 	char *argv[];
100 {
101 	struct kinfo_proc *ki = NULL;
102 	struct exec exec;
103 	int ch, cnt, efd, fd, sflag, uid;
104 	char *binfile, *corefile;
105 	char errbuf[_POSIX2_LINE_MAX], fname[MAXPATHLEN];
106 	int is_aout;
107 
108 	sflag = 0;
109 	corefile = NULL;
110         while ((ch = getopt(argc, argv, "c:s")) != -1) {
111                 switch (ch) {
112                 case 'c':
113 			corefile = optarg;
114                         break;
115 		case 's':
116 			sflag = 1;
117 			break;
118 		default:
119 			usage();
120 			break;
121 		}
122 	}
123 	argv += optind;
124 	argc -= optind;
125 
126 	/* XXX we should check that the pid argument is really a number */
127 	switch (argc) {
128 	case 1:
129 		pid = atoi(argv[0]);
130 		asprintf(&binfile, "/proc/%d/file", pid);
131 		if (binfile == NULL)
132 			errx(1, "allocation failure");
133 		break;
134 	case 2:
135 		pid = atoi(argv[1]);
136 		binfile = argv[0];
137 		break;
138 	default:
139 		usage();
140 	}
141 
142 	efd = open(binfile, O_RDONLY, 0);
143 	if (efd < 0)
144 		err(1, "%s", binfile);
145 
146 	cnt = read(efd, &exec, sizeof(exec));
147 	if (cnt != sizeof(exec))
148 		errx(1, "%s exec header: %s",
149 		    binfile, cnt > 0 ? strerror(EIO) : strerror(errno));
150 	if (!N_BADMAG(exec)) {
151 		is_aout = 1;
152 		/*
153 		 * This legacy a.out support uses the kvm interface instead
154 		 * of procfs.
155 		 */
156 		kd = kvm_openfiles(0, 0, 0, O_RDONLY, errbuf);
157 		if (kd == NULL)
158 			errx(1, "%s", errbuf);
159 
160 		uid = getuid();
161 
162 		ki = kvm_getprocs(kd, KERN_PROC_PID, pid, &cnt);
163 		if (ki == NULL || cnt != 1)
164 			errx(1, "%d: not found", pid);
165 
166 		if (ki->ki_ruid != uid && uid != 0)
167 			errx(1, "%d: not owner", pid);
168 
169 		if (ki->ki_stat == SZOMB)
170 			errx(1, "%d: zombie", pid);
171 
172 		if (ki->ki_flag & P_WEXIT)
173 			errx(1, "%d: process exiting", pid);
174 		if (ki->ki_flag & P_SYSTEM)	/* Swapper or pagedaemon. */
175 			errx(1, "%d: system process", pid);
176 		if (exec.a_text != ptoa(ki->ki_tsize))
177 			errx(1, "The executable %s does not belong to"
178 			    " process %d!\n"
179 			    "Text segment size (in bytes): executable %ld,"
180 			    " process %d", binfile, pid, exec.a_text,
181 			     ptoa(ki->ki_tsize));
182 		data_offset = N_DATOFF(exec);
183 	} else if (IS_ELF(*(Elf_Ehdr *)&exec)) {
184 		is_aout = 0;
185 		close(efd);
186 	} else
187 		errx(1, "Invalid executable file");
188 
189 	if (corefile == NULL) {
190 		(void)snprintf(fname, sizeof(fname), "core.%d", pid);
191 		corefile = fname;
192 	}
193 	fd = open(corefile, O_RDWR|O_CREAT|O_TRUNC, DEFFILEMODE);
194 	if (fd < 0)
195 		err(1, "%s", corefile);
196 
197 	if (sflag) {
198 		signal(SIGHUP, killed);
199 		signal(SIGINT, killed);
200 		signal(SIGTERM, killed);
201 		if (kill(pid, SIGSTOP) == -1)
202 			err(1, "%d: stop signal", pid);
203 		atexit(restart_target);
204 	}
205 
206 	if (is_aout)
207 		core(efd, fd, ki);
208 	else
209 		elf_coredump(fd, pid);
210 
211 	(void)close(fd);
212 	exit(0);
213 }
214 
215 /*
216  * core --
217  *	Build the core file.
218  */
219 void
220 core(efd, fd, ki)
221 	int efd;
222 	int fd;
223 	struct kinfo_proc *ki;
224 {
225 	union {
226 		struct user user;
227 		struct {
228 			char uabytes[ctob(UAREA_PAGES)];
229 			char ksbytes[ctob(KSTACK_PAGES)];
230 		} bytes;
231 	} uarea;
232 	int tsize = ki->ki_tsize;
233 	int dsize = ki->ki_dsize;
234 	int ssize = ki->ki_ssize;
235 	int cnt;
236 
237 	/* Read in user struct */
238 	cnt = kvm_read(kd, (u_long)ki->ki_addr, uarea.bytes.uabytes,
239 	    ctob(UAREA_PAGES));
240 	if (cnt != ctob(UAREA_PAGES))
241 		errx(1, "read upages structure: %s",
242 		    cnt > 0 ? strerror(EIO) : strerror(errno));
243 
244 	cnt = kvm_read(kd, (u_long)ki->ki_kstack, uarea.bytes.ksbytes,
245 	    ctob(KSTACK_PAGES));
246 	if (cnt != ctob(KSTACK_PAGES))
247 		errx(1, "read kstack structure: %s",
248 		    cnt > 0 ? strerror(EIO) : strerror(errno));
249 
250 	/*
251 	 * Fill in the eproc vm parameters, since these are garbage unless
252 	 * the kernel is dumping core or something.
253 	 */
254 	uarea.user.u_kproc = *ki;
255 
256 	/* Dump user area */
257 	cnt = write(fd, &uarea, sizeof(uarea));
258 	if (cnt != sizeof(uarea))
259 		errx(1, "write user structure: %s",
260 		    cnt > 0 ? strerror(EIO) : strerror(errno));
261 
262 	/* Dump data segment */
263 	datadump(efd, fd, ki, USRTEXT + ctob(tsize), dsize);
264 
265 	/* Dump stack segment */
266 	userdump(fd, ki, USRSTACK - ctob(ssize), ssize);
267 
268 	/* Dump machine dependent portions of the core. */
269 	md_core(kd, fd, ki);
270 }
271 
272 void
273 datadump(efd, fd, kp, addr, npage)
274 	register int efd;
275 	register int fd;
276 	struct kinfo_proc *kp;
277 	register u_long addr;
278 	register int npage;
279 {
280 	register int cc, delta;
281 	char buffer[PAGE_SIZE];
282 
283 	delta = data_offset - addr;
284 	while (--npage >= 0) {
285 		cc = kvm_uread(kd, kp, addr, buffer, PAGE_SIZE);
286 		if (cc != PAGE_SIZE) {
287 			/* Try to read the page from the executable. */
288 			if (lseek(efd, (off_t)addr + delta, SEEK_SET) == -1)
289 				err(1, "seek executable");
290 			cc = read(efd, buffer, sizeof(buffer));
291 			if (cc != sizeof(buffer)) {
292 				if (cc < 0)
293 					err(1, "read executable");
294 				else	/* Assume untouched bss page. */
295 					bzero(buffer, sizeof(buffer));
296 			}
297 		}
298 		cc = write(fd, buffer, PAGE_SIZE);
299 		if (cc != PAGE_SIZE)
300 			errx(1, "write data segment: %s",
301 			    cc > 0 ? strerror(EIO) : strerror(errno));
302 		addr += PAGE_SIZE;
303 	}
304 }
305 
306 static void
307 killed(sig)
308 	int sig;
309 {
310 	restart_target();
311 	signal(sig, SIG_DFL);
312 	kill(getpid(), sig);
313 }
314 
315 static void
316 restart_target()
317 {
318 	kill(pid, SIGCONT);
319 }
320 
321 void
322 userdump(fd, kp, addr, npage)
323 	register int fd;
324 	struct kinfo_proc *kp;
325 	register u_long addr;
326 	register int npage;
327 {
328 	register int cc;
329 	char buffer[PAGE_SIZE];
330 
331 	while (--npage >= 0) {
332 		cc = kvm_uread(kd, kp, addr, buffer, PAGE_SIZE);
333 		if (cc != PAGE_SIZE)
334 			/* Could be an untouched fill-with-zero page. */
335 			bzero(buffer, PAGE_SIZE);
336 		cc = write(fd, buffer, PAGE_SIZE);
337 		if (cc != PAGE_SIZE)
338 			errx(1, "write stack segment: %s",
339 			    cc > 0 ? strerror(EIO) : strerror(errno));
340 		addr += PAGE_SIZE;
341 	}
342 }
343 
344 void
345 usage()
346 {
347 	(void)fprintf(stderr, "usage: gcore [-s] [-c core] [executable] pid\n");
348 	exit(1);
349 }
350