xref: /freebsd/usr.bin/gcore/elfcore.c (revision 6b3455a7665208c366849f0b2b3bc916fb97516e)
1 /*-
2  * Copyright (c) 1998 John D. Polstra
3  * 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  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/procfs.h>
32 #include <sys/queue.h>
33 #include <sys/linker_set.h>
34 #include <machine/elf.h>
35 #include <vm/vm_param.h>
36 #include <vm/vm.h>
37 #include <vm/pmap.h>
38 #include <vm/vm_map.h>
39 #include <err.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <stdint.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47 
48 #include "extern.h"
49 
50 /*
51  * Code for generating ELF core dumps.
52  */
53 
54 typedef void (*segment_callback)(vm_map_entry_t, void *);
55 
56 /* Closure for cb_put_phdr(). */
57 struct phdr_closure {
58 	Elf_Phdr *phdr;		/* Program header to fill in */
59 	Elf_Off offset;		/* Offset of segment in core file */
60 };
61 
62 /* Closure for cb_size_segment(). */
63 struct sseg_closure {
64 	int count;		/* Count of writable segments. */
65 	size_t size;		/* Total size of all writable segments. */
66 };
67 
68 static void cb_put_phdr(vm_map_entry_t, void *);
69 static void cb_size_segment(vm_map_entry_t, void *);
70 static void each_writable_segment(vm_map_entry_t, segment_callback,
71     void *closure);
72 static void elf_corehdr(int fd, pid_t, vm_map_entry_t, int numsegs,
73     void *hdr, size_t hdrsize);
74 static void elf_puthdr(vm_map_entry_t, void *, size_t *,
75     const prstatus_t *, const prfpregset_t *, const prpsinfo_t *, int numsegs);
76 static void elf_putnote(void *dst, size_t *off, const char *name, int type,
77     const void *desc, size_t descsz);
78 static void freemap(vm_map_entry_t);
79 static void readhdrinfo(pid_t, prstatus_t *, prfpregset_t *, prpsinfo_t *);
80 static vm_map_entry_t readmap(pid_t);
81 
82 static int
83 elf_ident(int efd, pid_t pid __unused, char *binfile __unused)
84 {
85 	Elf_Ehdr hdr;
86 	int cnt;
87 
88 	cnt = read(efd, &hdr, sizeof(hdr));
89 	if (cnt != sizeof(hdr))
90 		return (0);
91 	if (IS_ELF(hdr))
92 		return (1);
93 	return (0);
94 }
95 
96 /*
97  * Write an ELF coredump for the given pid to the given fd.
98  */
99 static void
100 elf_coredump(int efd __unused, int fd, pid_t pid)
101 {
102 	vm_map_entry_t map;
103 	struct sseg_closure seginfo;
104 	void *hdr;
105 	size_t hdrsize;
106 	char memname[64];
107 	int memfd;
108 	Elf_Phdr *php;
109 	int i;
110 
111 	/* Get the program's memory map. */
112 	map = readmap(pid);
113 
114 	/* Size the program segments. */
115 	seginfo.count = 0;
116 	seginfo.size = 0;
117 	each_writable_segment(map, cb_size_segment, &seginfo);
118 
119 	/*
120 	 * Calculate the size of the core file header area by making
121 	 * a dry run of generating it.  Nothing is written, but the
122 	 * size is calculated.
123 	 */
124 	hdrsize = 0;
125 	elf_puthdr(map, (void *)NULL, &hdrsize,
126 	    (const prstatus_t *)NULL, (const prfpregset_t *)NULL,
127 	    (const prpsinfo_t *)NULL, seginfo.count);
128 
129 	/*
130 	 * Allocate memory for building the header, fill it up,
131 	 * and write it out.
132 	 */
133 	hdr = malloc(hdrsize);
134 	if ((hdr = malloc(hdrsize)) == NULL)
135 		errx(1, "out of memory");
136 	elf_corehdr(fd, pid, map, seginfo.count, hdr, hdrsize);
137 
138 	/* Write the contents of all of the writable segments. */
139 	snprintf(memname, sizeof memname, "/proc/%d/mem", pid);
140 	if ((memfd = open(memname, O_RDONLY)) == -1)
141 		err(1, "cannot open %s", memname);
142 
143 	php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
144 	for (i = 0;  i < seginfo.count;  i++) {
145 		uintmax_t nleft = php->p_filesz;
146 
147 		lseek(memfd, (off_t)php->p_vaddr, SEEK_SET);
148 		while (nleft > 0) {
149 			char buf[8*1024];
150 			size_t nwant;
151 			ssize_t ngot;
152 
153 			if (nleft > sizeof(buf))
154 				nwant = sizeof buf;
155 			else
156 				nwant = nleft;
157 			ngot = read(memfd, buf, nwant);
158 			if (ngot == -1)
159 				err(1, "read from %s", memname);
160 			if ((size_t)ngot < nwant)
161 				errx(1, "short read from %s:"
162 				    " wanted %d, got %d", memname,
163 				    nwant, ngot);
164 			ngot = write(fd, buf, nwant);
165 			if (ngot == -1)
166 				err(1, "write of segment %d failed", i);
167 			if ((size_t)ngot != nwant)
168 				errx(1, "short write");
169 			nleft -= nwant;
170 		}
171 		php++;
172 	}
173 	close(memfd);
174 	free(hdr);
175 	freemap(map);
176 }
177 
178 /*
179  * A callback for each_writable_segment() to write out the segment's
180  * program header entry.
181  */
182 static void
183 cb_put_phdr(vm_map_entry_t entry, void *closure)
184 {
185 	struct phdr_closure *phc = (struct phdr_closure *)closure;
186 	Elf_Phdr *phdr = phc->phdr;
187 
188 	phc->offset = round_page(phc->offset);
189 
190 	phdr->p_type = PT_LOAD;
191 	phdr->p_offset = phc->offset;
192 	phdr->p_vaddr = entry->start;
193 	phdr->p_paddr = 0;
194 	phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
195 	phdr->p_align = PAGE_SIZE;
196 	phdr->p_flags = 0;
197 	if (entry->protection & VM_PROT_READ)
198 		phdr->p_flags |= PF_R;
199 	if (entry->protection & VM_PROT_WRITE)
200 		phdr->p_flags |= PF_W;
201 	if (entry->protection & VM_PROT_EXECUTE)
202 		phdr->p_flags |= PF_X;
203 
204 	phc->offset += phdr->p_filesz;
205 	phc->phdr++;
206 }
207 
208 /*
209  * A callback for each_writable_segment() to gather information about
210  * the number of segments and their total size.
211  */
212 static void
213 cb_size_segment(vm_map_entry_t entry, void *closure)
214 {
215 	struct sseg_closure *ssc = (struct sseg_closure *)closure;
216 
217 	ssc->count++;
218 	ssc->size += entry->end - entry->start;
219 }
220 
221 /*
222  * For each segment in the given memory map, call the given function
223  * with a pointer to the map entry and some arbitrary caller-supplied
224  * data.
225  */
226 static void
227 each_writable_segment(vm_map_entry_t map, segment_callback func, void *closure)
228 {
229 	vm_map_entry_t entry;
230 
231 	for (entry = map;  entry != NULL;  entry = entry->next)
232 		(*func)(entry, closure);
233 }
234 
235 /*
236  * Write the core file header to the file, including padding up to
237  * the page boundary.
238  */
239 static void
240 elf_corehdr(int fd, pid_t pid, vm_map_entry_t map, int numsegs, void *hdr,
241     size_t hdrsize)
242 {
243 	size_t off;
244 	prstatus_t status;
245 	prfpregset_t fpregset;
246 	prpsinfo_t psinfo;
247 
248 	/* Gather the information for the header. */
249 	readhdrinfo(pid, &status, &fpregset, &psinfo);
250 
251 	/* Fill in the header. */
252 	memset(hdr, 0, hdrsize);
253 	off = 0;
254 	elf_puthdr(map, hdr, &off, &status, &fpregset, &psinfo, numsegs);
255 
256 	/* Write it to the core file. */
257 	if (write(fd, hdr, hdrsize) == -1)
258 		err(1, "write");
259 }
260 
261 /*
262  * Generate the ELF coredump header into the buffer at "dst".  "dst" may
263  * be NULL, in which case the header is sized but not actually generated.
264  */
265 static void
266 elf_puthdr(vm_map_entry_t map, void *dst, size_t *off, const prstatus_t *status,
267     const prfpregset_t *fpregset, const prpsinfo_t *psinfo, int numsegs)
268 {
269 	size_t ehoff;
270 	size_t phoff;
271 	size_t noteoff;
272 	size_t notesz;
273 
274 	ehoff = *off;
275 	*off += sizeof(Elf_Ehdr);
276 
277 	phoff = *off;
278 	*off += (numsegs + 1) * sizeof(Elf_Phdr);
279 
280 	noteoff = *off;
281 	elf_putnote(dst, off, "FreeBSD", NT_PRSTATUS, status,
282 	    sizeof *status);
283 	elf_putnote(dst, off, "FreeBSD", NT_FPREGSET, fpregset,
284 	    sizeof *fpregset);
285 	elf_putnote(dst, off, "FreeBSD", NT_PRPSINFO, psinfo,
286 	    sizeof *psinfo);
287 	notesz = *off - noteoff;
288 
289 	/* Align up to a page boundary for the program segments. */
290 	*off = round_page(*off);
291 
292 	if (dst != NULL) {
293 		Elf_Ehdr *ehdr;
294 		Elf_Phdr *phdr;
295 		struct phdr_closure phc;
296 
297 		/*
298 		 * Fill in the ELF header.
299 		 */
300 		ehdr = (Elf_Ehdr *)((char *)dst + ehoff);
301 		ehdr->e_ident[EI_MAG0] = ELFMAG0;
302 		ehdr->e_ident[EI_MAG1] = ELFMAG1;
303 		ehdr->e_ident[EI_MAG2] = ELFMAG2;
304 		ehdr->e_ident[EI_MAG3] = ELFMAG3;
305 		ehdr->e_ident[EI_CLASS] = ELF_CLASS;
306 		ehdr->e_ident[EI_DATA] = ELF_DATA;
307 		ehdr->e_ident[EI_VERSION] = EV_CURRENT;
308 		ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
309 		ehdr->e_ident[EI_ABIVERSION] = 0;
310 		ehdr->e_ident[EI_PAD] = 0;
311 		ehdr->e_type = ET_CORE;
312 		ehdr->e_machine = ELF_ARCH;
313 		ehdr->e_version = EV_CURRENT;
314 		ehdr->e_entry = 0;
315 		ehdr->e_phoff = phoff;
316 		ehdr->e_flags = 0;
317 		ehdr->e_ehsize = sizeof(Elf_Ehdr);
318 		ehdr->e_phentsize = sizeof(Elf_Phdr);
319 		ehdr->e_phnum = numsegs + 1;
320 		ehdr->e_shentsize = sizeof(Elf_Shdr);
321 		ehdr->e_shnum = 0;
322 		ehdr->e_shstrndx = SHN_UNDEF;
323 
324 		/*
325 		 * Fill in the program header entries.
326 		 */
327 		phdr = (Elf_Phdr *)((char *)dst + phoff);
328 
329 		/* The note segment. */
330 		phdr->p_type = PT_NOTE;
331 		phdr->p_offset = noteoff;
332 		phdr->p_vaddr = 0;
333 		phdr->p_paddr = 0;
334 		phdr->p_filesz = notesz;
335 		phdr->p_memsz = 0;
336 		phdr->p_flags = 0;
337 		phdr->p_align = 0;
338 		phdr++;
339 
340 		/* All the writable segments from the program. */
341 		phc.phdr = phdr;
342 		phc.offset = *off;
343 		each_writable_segment(map, cb_put_phdr, &phc);
344 	}
345 }
346 
347 /*
348  * Emit one note section to "dst", or just size it if "dst" is NULL.
349  */
350 static void
351 elf_putnote(void *dst, size_t *off, const char *name, int type,
352     const void *desc, size_t descsz)
353 {
354 	Elf_Note note;
355 
356 	note.n_namesz = strlen(name) + 1;
357 	note.n_descsz = descsz;
358 	note.n_type = type;
359 	if (dst != NULL)
360 		bcopy(&note, (char *)dst + *off, sizeof note);
361 	*off += sizeof note;
362 	if (dst != NULL)
363 		bcopy(name, (char *)dst + *off, note.n_namesz);
364 	*off += roundup2(note.n_namesz, sizeof(Elf_Size));
365 	if (dst != NULL)
366 		bcopy(desc, (char *)dst + *off, note.n_descsz);
367 	*off += roundup2(note.n_descsz, sizeof(Elf_Size));
368 }
369 
370 /*
371  * Free the memory map.
372  */
373 static void
374 freemap(vm_map_entry_t map)
375 {
376 
377 	while (map != NULL) {
378 		vm_map_entry_t next = map->next;
379 		free(map);
380 		map = next;
381 	}
382 }
383 
384 /*
385  * Read the process information necessary to fill in the core file's header.
386  */
387 static void
388 readhdrinfo(pid_t pid, prstatus_t *status, prfpregset_t *fpregset,
389     prpsinfo_t *psinfo)
390 {
391 	char name[64];
392 	char line[256];
393 	int fd;
394 	int i;
395 	int n;
396 
397 	memset(status, 0, sizeof *status);
398 	status->pr_version = PRSTATUS_VERSION;
399 	status->pr_statussz = sizeof(prstatus_t);
400 	status->pr_gregsetsz = sizeof(gregset_t);
401 	status->pr_fpregsetsz = sizeof(fpregset_t);
402 	status->pr_osreldate = __FreeBSD_version;
403 	status->pr_pid = pid;
404 
405 	memset(fpregset, 0, sizeof *fpregset);
406 
407 	memset(psinfo, 0, sizeof *psinfo);
408 	psinfo->pr_version = PRPSINFO_VERSION;
409 	psinfo->pr_psinfosz = sizeof(prpsinfo_t);
410 
411 	/* Read the general registers. */
412 	snprintf(name, sizeof name, "/proc/%d/regs", pid);
413 	if ((fd = open(name, O_RDONLY)) == -1)
414 		err(1, "cannot open %s", name);
415 	if ((n = read(fd, &status->pr_reg, sizeof status->pr_reg)) == -1)
416 		err(1, "read error from %s", name);
417 	if ((size_t)n < sizeof(status->pr_reg))
418 		errx(1, "short read from %s: wanted %u, got %d", name,
419 		    sizeof status->pr_reg, n);
420 	close(fd);
421 
422 	/* Read the floating point registers. */
423 	snprintf(name, sizeof name, "/proc/%d/fpregs", pid);
424 	if ((fd = open(name, O_RDONLY)) == -1)
425 		err(1, "cannot open %s", name);
426 	if ((n = read(fd, fpregset, sizeof *fpregset)) == -1)
427 		err(1, "read error from %s", name);
428 	if ((size_t)n < sizeof(*fpregset))
429 		errx(1, "short read from %s: wanted %u, got %d", name,
430 		    sizeof *fpregset, n);
431 	close(fd);
432 
433 	/* Read and parse the process status. */
434 	snprintf(name, sizeof name, "/proc/%d/status", pid);
435 	if ((fd = open(name, O_RDONLY)) == -1)
436 		err(1, "cannot open %s", name);
437 	if ((n = read(fd, line, sizeof line - 1)) == -1)
438 		err(1, "read error from %s", name);
439 	if (n > MAXCOMLEN)
440 		n = MAXCOMLEN;
441 	for (i = 0;  i < n && line[i] != ' ';  i++)
442 		psinfo->pr_fname[i] = line[i];
443 	strncpy(psinfo->pr_psargs, psinfo->pr_fname, PRARGSZ);
444 	close(fd);
445 }
446 
447 /*
448  * Read the process's memory map using procfs, and return a list of
449  * VM map entries.  Only the non-device read/writable segments are
450  * returned.  The map entries in the list aren't fully filled in; only
451  * the items we need are present.
452  */
453 static vm_map_entry_t
454 readmap(pid_t pid)
455 {
456 	char mapname[64];
457 	int mapfd;
458 	ssize_t mapsize;
459 	size_t bufsize;
460 	char *mapbuf;
461 	int pos;
462 	vm_map_entry_t map;
463 	vm_map_entry_t *linkp;
464 
465 	snprintf(mapname, sizeof mapname, "/proc/%d/map", pid);
466 	if ((mapfd = open(mapname, O_RDONLY)) == -1)
467 		err(1, "cannot open %s", mapname);
468 
469 	/*
470 	 * Procfs requires (for consistency) that the entire memory map
471 	 * be read with a single read() call.  Start with a reasonably sized
472 	 * buffer, and double it until it is big enough.
473 	 */
474 	bufsize = 8 * 1024;
475 	mapbuf = NULL;
476 	for ( ; ; ) {
477 		if ((mapbuf = realloc(mapbuf, bufsize + 1)) == NULL)
478 			errx(1, "out of memory");
479 		mapsize = read(mapfd, mapbuf, bufsize);
480 		if (mapsize != -1 || errno != EFBIG)
481 			break;
482 		bufsize *= 2;
483 		/* This lseek shouldn't be necessary, but it is. */
484 		lseek(mapfd, (off_t)0, SEEK_SET);
485 	}
486 	if (mapsize == -1)
487 		err(1, "read error from %s", mapname);
488 	if (mapsize == 0)
489 		errx(1, "empty map file %s", mapname);
490 	mapbuf[mapsize] = 0;
491 	close(mapfd);
492 
493 	pos = 0;
494 	map = NULL;
495 	linkp = &map;
496 	while (pos < mapsize) {
497 		vm_map_entry_t ent;
498 		vm_offset_t start;
499 		vm_offset_t end;
500 		char prot[4];
501 		char type[16];
502 		int n;
503 		int len;
504 
505 		len = 0;
506 		n = sscanf(mapbuf + pos, "%x %x %*d %*d %*x %3[-rwx]"
507 		    " %*d %*d %*x %*s %*s %16s %*s%*[\n]%n",
508 		    &start, &end, prot, type, &len);
509 		if (n != 4 || len == 0)
510 			errx(1, "ill-formed line in %s starting at character %d", mapname, pos + 1);
511 		pos += len;
512 
513 		/* Ignore segments of the wrong kind, and unwritable ones */
514 		if (strncmp(prot, "rw", 2) != 0 ||
515 		    (strcmp(type, "default") != 0 &&
516 		    strcmp(type, "vnode") != 0 &&
517 		    strcmp(type, "swap") != 0))
518 			continue;
519 
520 		if ((ent = (vm_map_entry_t)calloc(1, sizeof *ent)) == NULL)
521 			errx(1, "out of memory");
522 		ent->start = start;
523 		ent->end = end;
524 		ent->protection = VM_PROT_READ | VM_PROT_WRITE;
525 		if (prot[2] == 'x')
526 		    ent->protection |= VM_PROT_EXECUTE;
527 
528 		*linkp = ent;
529 		linkp = &ent->next;
530 	}
531 	free(mapbuf);
532 	return map;
533 }
534 
535 struct dumpers elfdump = { elf_ident, elf_coredump };
536 TEXT_SET(dumpset, elfdump);
537