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