xref: /freebsd-13.1/lib/libprocstat/core.c (revision 4482b5e3)
1 /*-
2  * Copyright (c) 2013 Mikolaj Golub <[email protected]>
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 REGENTS 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 REGENTS 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  * $FreeBSD$
27  */
28 
29 #include <sys/param.h>
30 #include <sys/elf.h>
31 #include <sys/exec.h>
32 #include <sys/user.h>
33 
34 #include <assert.h>
35 #include <err.h>
36 #include <fcntl.h>
37 #include <gelf.h>
38 #include <libelf.h>
39 #include <stdbool.h>
40 #include <stdint.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 
46 #include "core.h"
47 
48 #define PROCSTAT_CORE_MAGIC	0x012DADB8
49 struct procstat_core
50 {
51 	int		pc_magic;
52 	int		pc_fd;
53 	Elf		*pc_elf;
54 	GElf_Ehdr	pc_ehdr;
55 	GElf_Phdr	pc_phdr;
56 };
57 
58 static bool	core_offset(struct procstat_core *core, off_t offset);
59 static bool	core_read(struct procstat_core *core, void *buf, size_t len);
60 static ssize_t	core_read_mem(struct procstat_core *core, void *buf,
61     size_t len, vm_offset_t addr, bool readall);
62 static void	*get_args(struct procstat_core *core, vm_offset_t psstrings,
63     enum psc_type type, void *buf, size_t *lenp);
64 
65 struct procstat_core *
66 procstat_core_open(const char *filename)
67 {
68 	struct procstat_core *core;
69 	Elf *e;
70 	GElf_Ehdr ehdr;
71 	GElf_Phdr phdr;
72 	size_t nph;
73 	int fd, i;
74 
75 	if (elf_version(EV_CURRENT) == EV_NONE) {
76 		warnx("ELF library too old");
77 		return (NULL);
78 	}
79 	fd = open(filename, O_RDONLY, 0);
80 	if (fd == -1) {
81 		warn("open(%s)", filename);
82 		return (NULL);
83 	}
84 	e = elf_begin(fd, ELF_C_READ, NULL);
85 	if (e == NULL) {
86 		warnx("elf_begin: %s", elf_errmsg(-1));
87 		goto fail;
88 	}
89 	if (elf_kind(e) != ELF_K_ELF) {
90 		warnx("%s is not an ELF object", filename);
91 		goto fail;
92 	}
93 	if (gelf_getehdr(e, &ehdr) == NULL) {
94 		warnx("gelf_getehdr: %s", elf_errmsg(-1));
95 		goto fail;
96 	}
97 	if (ehdr.e_type != ET_CORE) {
98 		warnx("%s is not a CORE file", filename);
99 		goto fail;
100 	}
101 	if (elf_getphnum(e, &nph) == 0) {
102 		warnx("program headers not found");
103 		goto fail;
104 	}
105 	for (i = 0; i < ehdr.e_phnum; i++) {
106 		if (gelf_getphdr(e, i, &phdr) != &phdr) {
107 			warnx("gelf_getphdr: %s", elf_errmsg(-1));
108 			goto fail;
109 		}
110 		if (phdr.p_type == PT_NOTE)
111 			break;
112 	}
113 	if (i == ehdr.e_phnum) {
114 		warnx("NOTE program header not found");
115 		goto fail;
116 	}
117 	core = malloc(sizeof(struct procstat_core));
118 	if (core == NULL) {
119 		warn("malloc(%zu)", sizeof(struct procstat_core));
120 		goto fail;
121 	}
122 	core->pc_magic = PROCSTAT_CORE_MAGIC;
123 	core->pc_fd = fd;
124 	core->pc_elf = e;
125 	core->pc_ehdr = ehdr;
126 	core->pc_phdr = phdr;
127 
128 	return (core);
129 fail:
130 	if (e != NULL)
131 		elf_end(e);
132 	close(fd);
133 
134 	return (NULL);
135 }
136 
137 void
138 procstat_core_close(struct procstat_core *core)
139 {
140 
141 	assert(core->pc_magic == PROCSTAT_CORE_MAGIC);
142 
143 	elf_end(core->pc_elf);
144 	close(core->pc_fd);
145 	free(core);
146 }
147 
148 void *
149 procstat_core_get(struct procstat_core *core, enum psc_type type, void *buf,
150     size_t *lenp)
151 {
152 	Elf_Note nhdr;
153 	off_t offset, eoffset;
154 	vm_offset_t psstrings;
155 	void *freebuf;
156 	size_t len;
157 	u_int32_t n_type;
158 	int cstructsize, structsize;
159 	char nbuf[8];
160 
161 	assert(core->pc_magic == PROCSTAT_CORE_MAGIC);
162 
163 	switch(type) {
164 	case PSC_TYPE_PROC:
165 		n_type = NT_PROCSTAT_PROC;
166 		structsize = sizeof(struct kinfo_proc);
167 		break;
168 	case PSC_TYPE_FILES:
169 		n_type = NT_PROCSTAT_FILES;
170 		structsize = sizeof(struct kinfo_file);
171 		break;
172 	case PSC_TYPE_VMMAP:
173 		n_type = NT_PROCSTAT_VMMAP;
174 		structsize = sizeof(struct kinfo_vmentry);
175 		break;
176 	case PSC_TYPE_GROUPS:
177 		n_type = NT_PROCSTAT_GROUPS;
178 		structsize = sizeof(gid_t);
179 		break;
180 	case PSC_TYPE_UMASK:
181 		n_type = NT_PROCSTAT_UMASK;
182 		structsize = sizeof(u_short);
183 		break;
184 	case PSC_TYPE_RLIMIT:
185 		n_type = NT_PROCSTAT_RLIMIT;
186 		structsize = sizeof(struct rlimit) * RLIM_NLIMITS;
187 		break;
188 	case PSC_TYPE_OSREL:
189 		n_type = NT_PROCSTAT_OSREL;
190 		structsize = sizeof(int);
191 		break;
192 	case PSC_TYPE_PSSTRINGS:
193 	case PSC_TYPE_ARGV:
194 	case PSC_TYPE_ENVV:
195 		n_type = NT_PROCSTAT_PSSTRINGS;
196 		structsize = sizeof(vm_offset_t);
197 		break;
198 	default:
199 		warnx("unknown core stat type: %d", type);
200 		return (NULL);
201 	}
202 
203 	offset = core->pc_phdr.p_offset;
204 	eoffset = offset + core->pc_phdr.p_filesz;
205 
206 	while (offset < eoffset) {
207 		if (!core_offset(core, offset))
208 			return (NULL);
209 		if (!core_read(core, &nhdr, sizeof(nhdr)))
210 			return (NULL);
211 
212 		offset += sizeof(nhdr) +
213 		    roundup2(nhdr.n_namesz, sizeof(Elf32_Size)) +
214 		    roundup2(nhdr.n_descsz, sizeof(Elf32_Size));
215 
216 		if (nhdr.n_namesz == 0 && nhdr.n_descsz == 0)
217 			break;
218 		if (nhdr.n_type != n_type)
219 			continue;
220 		if (nhdr.n_namesz != 8)
221 			continue;
222 		if (!core_read(core, nbuf, sizeof(nbuf)))
223 			return (NULL);
224 		if (strcmp(nbuf, "FreeBSD") != 0)
225 			continue;
226 		if (nhdr.n_descsz < sizeof(cstructsize)) {
227 			warnx("corrupted core file");
228 			return (NULL);
229 		}
230 		if (!core_read(core, &cstructsize, sizeof(cstructsize)))
231 			return (NULL);
232 		if (cstructsize != structsize) {
233 			warnx("version mismatch");
234 			return (NULL);
235 		}
236 		len = nhdr.n_descsz - sizeof(cstructsize);
237 		if (len == 0)
238 			return (NULL);
239 		if (buf != NULL) {
240 			len = MIN(len, *lenp);
241 			freebuf = NULL;
242 		} else {
243 			freebuf = buf = malloc(len);
244 			if (buf == NULL) {
245 				warn("malloc(%zu)", len);
246 				return (NULL);
247 			}
248 		}
249 		if (!core_read(core, buf, len)) {
250 			free(freebuf);
251 			return (NULL);
252 		}
253 		if (type == PSC_TYPE_ARGV || type == PSC_TYPE_ENVV) {
254 			if (len < sizeof(psstrings)) {
255 				free(freebuf);
256 				return (NULL);
257 			}
258 			psstrings = *(vm_offset_t *)buf;
259 			if (freebuf == NULL)
260 				len = *lenp;
261 			else
262 				buf = NULL;
263 			free(freebuf);
264 			buf = get_args(core, psstrings, type, buf, &len);
265 		}
266 		*lenp = len;
267 		return (buf);
268         }
269 
270 	return (NULL);
271 }
272 
273 static bool
274 core_offset(struct procstat_core *core, off_t offset)
275 {
276 
277 	assert(core->pc_magic == PROCSTAT_CORE_MAGIC);
278 
279 	if (lseek(core->pc_fd, offset, SEEK_SET) == -1) {
280 		warn("core: lseek(%jd)", (intmax_t)offset);
281 		return (false);
282 	}
283 	return (true);
284 }
285 
286 static bool
287 core_read(struct procstat_core *core, void *buf, size_t len)
288 {
289 	ssize_t n;
290 
291 	assert(core->pc_magic == PROCSTAT_CORE_MAGIC);
292 
293 	n = read(core->pc_fd, buf, len);
294 	if (n == -1) {
295 		warn("core: read");
296 		return (false);
297 	}
298 	if (n < (ssize_t)len) {
299 		warnx("core: short read");
300 		return (false);
301 	}
302 	return (true);
303 }
304 
305 static ssize_t
306 core_read_mem(struct procstat_core *core, void *buf, size_t len,
307     vm_offset_t addr, bool readall)
308 {
309 	GElf_Phdr phdr;
310 	off_t offset;
311 	int i;
312 
313 	assert(core->pc_magic == PROCSTAT_CORE_MAGIC);
314 
315 	for (i = 0; i < core->pc_ehdr.e_phnum; i++) {
316 		if (gelf_getphdr(core->pc_elf, i, &phdr) != &phdr) {
317 			warnx("gelf_getphdr: %s", elf_errmsg(-1));
318 			return (-1);
319 		}
320 		if (phdr.p_type != PT_LOAD)
321 			continue;
322 		if (addr < phdr.p_vaddr || addr > phdr.p_vaddr + phdr.p_memsz)
323 			continue;
324 		offset = phdr.p_offset + (addr - phdr.p_vaddr);
325 		if ((phdr.p_vaddr + phdr.p_memsz) - addr < len) {
326 			if (readall) {
327 				warnx("format error: "
328 				    "attempt to read out of segment");
329 				return (-1);
330 			}
331 			len = (phdr.p_vaddr + phdr.p_memsz) - addr;
332 		}
333 		if (!core_offset(core, offset))
334 			return (-1);
335 		if (!core_read(core, buf, len))
336 			return (-1);
337 		return (len);
338 	}
339 	warnx("format error: address %ju not found", (uintmax_t)addr);
340 	return (-1);
341 }
342 
343 #define ARGS_CHUNK_SZ	256	/* Chunk size (bytes) for get_args operations. */
344 
345 static void *
346 get_args(struct procstat_core *core, vm_offset_t psstrings, enum psc_type type,
347      void *args, size_t *lenp)
348 {
349 	struct ps_strings pss;
350 	void *freeargs;
351 	vm_offset_t addr;
352 	char **argv, *p;
353 	size_t chunksz, done, len, nchr, size;
354 	ssize_t n;
355 	u_int i, nstr;
356 
357 	assert(type == PSC_TYPE_ARGV || type == PSC_TYPE_ENVV);
358 
359 	if (core_read_mem(core, &pss, sizeof(pss), psstrings, true) == -1)
360 		return (NULL);
361 	if (type == PSC_TYPE_ARGV) {
362 		addr = (vm_offset_t)pss.ps_argvstr;
363 		nstr = pss.ps_nargvstr;
364 	} else /* type == PSC_TYPE_ENVV */ {
365 		addr = (vm_offset_t)pss.ps_envstr;
366 		nstr = pss.ps_nenvstr;
367 	}
368 	if (addr == 0 || nstr == 0)
369 		return (NULL);
370 	if (nstr > ARG_MAX) {
371 		warnx("format error");
372 		return (NULL);
373 	}
374 	size = nstr * sizeof(char *);
375 	argv = malloc(size);
376 	if (argv == NULL) {
377 		warn("malloc(%zu)", size);
378 		return (NULL);
379 	}
380 	done = 0;
381 	freeargs = NULL;
382 	if (core_read_mem(core, argv, size, addr, true) == -1)
383 		goto fail;
384 	if (args != NULL) {
385 		nchr = MIN(ARG_MAX, *lenp);
386 	} else {
387 		nchr = ARG_MAX;
388 		freeargs = args = malloc(nchr);
389 		if (args == NULL) {
390 			warn("malloc(%zu)", nchr);
391 			goto fail;
392 		}
393 	}
394 	p = args;
395 	for (i = 0; ; i++) {
396 		if (i == nstr)
397 			goto done;
398 		/*
399 		 * The program may have scribbled into its argv array, e.g. to
400 		 * remove some arguments.  If that has happened, break out
401 		 * before trying to read from NULL.
402 		 */
403 		if (argv[i] == NULL)
404 			goto done;
405 		for (addr = (vm_offset_t)argv[i]; ; addr += chunksz) {
406 			chunksz = MIN(ARGS_CHUNK_SZ, nchr - 1 - done);
407 			if (chunksz <= 0)
408 				goto done;
409 			n = core_read_mem(core, p, chunksz, addr, false);
410 			if (n == -1)
411 				goto fail;
412 			len = strnlen(p, chunksz);
413 			p += len;
414 			done += len;
415 			if (len != chunksz)
416 				break;
417 		}
418 		*p++ = '\0';
419 		done++;
420 	}
421 fail:
422 	free(freeargs);
423 	args = NULL;
424 done:
425 	*lenp = done;
426 	free(argv);
427 	return (args);
428 }
429