xref: /freebsd/usr.bin/ldd/ldd.c (revision 4d846d26)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1993 Paul Kranenburg
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *      This product includes software developed by Paul Kranenburg.
18  * 4. The name of the author may not be used to endorse or promote products
19  *    derived from this software without specific prior written permission
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include <sys/param.h>
37 #include <sys/wait.h>
38 
39 #include <machine/elf.h>
40 
41 #include <arpa/inet.h>
42 
43 #include <dlfcn.h>
44 #include <err.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <gelf.h>
48 #include <libelf.h>
49 #include <rtld_paths.h>
50 #include <stdbool.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 
56 /*
57  * 32-bit ELF data structures can only be used if the system header[s] declare
58  * them.  There is no official macro for determining whether they are declared,
59  * so check for the existence of one of the 32-macros defined in elf(5).
60  */
61 #ifdef ELF32_R_TYPE
62 #define	ELF32_SUPPORTED
63 #endif
64 
65 #define	LDD_SETENV(name, value, overwrite) do {		\
66 	setenv("LD_" name, value, overwrite);		\
67 	setenv("LD_32_" name, value, overwrite);	\
68 } while (0)
69 
70 #define	LDD_UNSETENV(name) do {		\
71 	unsetenv("LD_" name);		\
72 	unsetenv("LD_32_" name);	\
73 } while (0)
74 
75 static int	is_executable(const char *fname, int fd, int *is_shlib,
76 		    int *type);
77 static void	usage(void);
78 
79 #define	TYPE_UNKNOWN	0
80 #define	TYPE_ELF	1	/* Architecture default */
81 #if __ELF_WORD_SIZE > 32 && defined(ELF32_SUPPORTED)
82 #define	TYPE_ELF32	2	/* Explicit 32 bits on architectures >32 bits */
83 
84 #define	_PATH_LDD32	"/usr/bin/ldd32"
85 
86 static int
87 execldd32(char *file, char *fmt1, char *fmt2, int aflag)
88 {
89 	char *argv[9];
90 	int i, rval, status;
91 
92 	LDD_UNSETENV("TRACE_LOADED_OBJECTS");
93 	rval = 0;
94 	i = 0;
95 	argv[i++] = strdup(_PATH_LDD32);
96 	if (aflag)
97 		argv[i++] = strdup("-a");
98 	if (fmt1 != NULL) {
99 		argv[i++] = strdup("-f");
100 		argv[i++] = strdup(fmt1);
101 	}
102 	if (fmt2 != NULL) {
103 		argv[i++] = strdup("-f");
104 		argv[i++] = strdup(fmt2);
105 	}
106 	argv[i++] = strdup(file);
107 	argv[i++] = NULL;
108 
109 	switch (fork()) {
110 	case -1:
111 		err(1, "fork");
112 		break;
113 	case 0:
114 		execv(_PATH_LDD32, argv);
115 		warn("%s", _PATH_LDD32);
116 		_exit(127);
117 		break;
118 	default:
119 		if (wait(&status) < 0)
120 			rval = 1;
121 		else if (WIFSIGNALED(status))
122 			rval = 1;
123 		else if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
124 			rval = 1;
125 		break;
126 	}
127 	while (i--)
128 		free(argv[i]);
129 	LDD_SETENV("TRACE_LOADED_OBJECTS", "yes", 1);
130 	return (rval);
131 }
132 #endif
133 
134 int
135 main(int argc, char *argv[])
136 {
137 	char *fmt1, *fmt2;
138 	const char *rtld;
139 	int aflag, c, fd, rval, status, is_shlib, rv, type;
140 
141 	aflag = 0;
142 	fmt1 = fmt2 = NULL;
143 
144 	while ((c = getopt(argc, argv, "af:")) != -1) {
145 		switch (c) {
146 		case 'a':
147 			aflag++;
148 			break;
149 		case 'f':
150 			if (fmt1 != NULL) {
151 				if (fmt2 != NULL)
152 					errx(1, "too many formats");
153 				fmt2 = optarg;
154 			} else
155 				fmt1 = optarg;
156 			break;
157 		default:
158 			usage();
159 			/* NOTREACHED */
160 		}
161 	}
162 	argc -= optind;
163 	argv += optind;
164 
165 	if (argc <= 0) {
166 		usage();
167 		/* NOTREACHED */
168 	}
169 
170 	rval = 0;
171 	for (; argc > 0; argc--, argv++) {
172 		if ((fd = open(*argv, O_RDONLY | O_VERIFY, 0)) < 0) {
173 			warn("%s", *argv);
174 			rval |= 1;
175 			continue;
176 		}
177 		rv = is_executable(*argv, fd, &is_shlib, &type);
178 		close(fd);
179 		if (rv == 0) {
180 			rval |= 1;
181 			continue;
182 		}
183 
184 		switch (type) {
185 		case TYPE_ELF:
186 			break;
187 #if __ELF_WORD_SIZE > 32 && defined(ELF32_SUPPORTED)
188 		case TYPE_ELF32:
189 			rval |= execldd32(*argv, fmt1, fmt2, aflag);
190 			continue;
191 #endif
192 		case TYPE_UNKNOWN:
193 		default:
194 			/*
195 			 * This shouldn't happen unless is_executable()
196 			 * is broken.
197 			 */
198 			errx(EDOOFUS, "unknown executable type");
199 		}
200 
201 		/* ld.so magic */
202 		LDD_SETENV("TRACE_LOADED_OBJECTS", "yes", 1);
203 		if (fmt1 != NULL)
204 			LDD_SETENV("TRACE_LOADED_OBJECTS_FMT1", fmt1, 1);
205 		if (fmt2 != NULL)
206 			LDD_SETENV("TRACE_LOADED_OBJECTS_FMT2", fmt2, 1);
207 
208 		LDD_SETENV("TRACE_LOADED_OBJECTS_PROGNAME", *argv, 1);
209 		if (aflag)
210 			LDD_SETENV("TRACE_LOADED_OBJECTS_ALL", "1", 1);
211 		else if (fmt1 == NULL && fmt2 == NULL)
212 			/* Default formats */
213 			printf("%s:\n", *argv);
214 		fflush(stdout);
215 
216 		switch (fork()) {
217 		case -1:
218 			err(1, "fork");
219 			break;
220 		default:
221 			if (wait(&status) < 0) {
222 				warn("wait");
223 				rval |= 1;
224 			} else if (WIFSIGNALED(status)) {
225 				fprintf(stderr, "%s: signal %d\n", *argv,
226 				    WTERMSIG(status));
227 				rval |= 1;
228 			} else if (WIFEXITED(status) &&
229 			    WEXITSTATUS(status) != 0) {
230 				fprintf(stderr, "%s: exit status %d\n", *argv,
231 				    WEXITSTATUS(status));
232 				rval |= 1;
233 			}
234 			break;
235 		case 0:
236 			rtld = _PATH_RTLD;
237 #if __ELF_WORD_SIZE > 32 && defined(ELF32_SUPPORTED)
238 			if (type == TYPE_ELF32)
239 				rtld = _COMPAT32_PATH_RTLD;
240 #endif
241 			if (is_shlib == 0) {
242 				execl(rtld, rtld, "--",
243 				    *argv, (char *)NULL);
244 				warn("%s", *argv);
245 			} else if (fmt1 == NULL && fmt2 == NULL && !aflag) {
246 				dlopen(*argv, RTLD_TRACE);
247 				warnx("%s: %s", *argv, dlerror());
248 			} else {
249 				execl(rtld, rtld, "-d", "--",
250 				    *argv, (char *)NULL);
251 			}
252 			_exit(1);
253 		}
254 	}
255 
256 	return (rval);
257 }
258 
259 static void
260 usage(void)
261 {
262 
263 	fprintf(stderr,
264 	    "usage: ldd [-a] [-f format [-f format]] program ...\n");
265 	exit(1);
266 }
267 
268 static bool
269 has_freebsd_abi_tag(const char *fname, Elf *elf, GElf_Ehdr *ehdr, off_t offset,
270     size_t len)
271 {
272 	Elf_Data dst, src;
273 	const Elf_Note *note;
274 	char *buf;
275 	const char *name;
276 	void *copy;
277 	size_t namesz, descsz;
278 	bool has_abi_tag;
279 
280 	buf = elf_rawfile(elf, NULL);
281 	if (buf == NULL) {
282 		warnx("%s: %s", fname, elf_errmsg(0));
283 		return (false);
284 	}
285 
286 	memset(&src, 0, sizeof(src));
287 	src.d_buf = buf + offset;
288 	src.d_size = len;
289 	src.d_type = ELF_T_NOTE;
290 	src.d_version = EV_CURRENT;
291 
292 	memset(&dst, 0, sizeof(dst));
293 	dst.d_buf = copy = malloc(len);
294 	dst.d_size = len;
295 	dst.d_type = ELF_T_NOTE;
296 	dst.d_version = EV_CURRENT;
297 
298 	if (gelf_xlatetom(elf, &dst, &src, ehdr->e_ident[EI_DATA]) == NULL) {
299 		warnx("%s: failed to parse notes: %s", fname, elf_errmsg(0));
300 		free(copy);
301 		return (false);
302 	}
303 
304 	buf = copy;
305 	has_abi_tag = false;
306 	for (;;) {
307 		if (len < sizeof(*note))
308 			break;
309 
310 		note = (const void *)buf;
311 		buf += sizeof(*note);
312 		len -= sizeof(*note);
313 
314 		namesz = roundup2(note->n_namesz, sizeof(uint32_t));
315 		descsz = roundup2(note->n_descsz, sizeof(uint32_t));
316 		if (len < namesz + descsz)
317 			break;
318 
319 		name = buf;
320 		if (note->n_namesz == sizeof(ELF_NOTE_FREEBSD) &&
321 		    strncmp(name, ELF_NOTE_FREEBSD, note->n_namesz) == 0 &&
322 		    note->n_type == NT_FREEBSD_ABI_TAG &&
323 		    note->n_descsz == sizeof(uint32_t)) {
324 			has_abi_tag = true;
325 			break;
326 		}
327 
328 		buf += namesz + descsz;
329 		len -= namesz + descsz;
330 	}
331 
332 	free(copy);
333 	return (has_abi_tag);
334 }
335 
336 static bool
337 is_pie(const char *fname, Elf *elf, GElf_Ehdr *ehdr, off_t offset, size_t len)
338 {
339 	Elf_Data dst, src;
340 	char *buf;
341 	void *copy;
342 	const GElf_Dyn *dyn;
343 	size_t dynsize;
344 	u_int count, i;
345 	bool pie;
346 
347 	buf = elf_rawfile(elf, NULL);
348 	if (buf == NULL) {
349 		warnx("%s: %s", fname, elf_errmsg(0));
350 		return (false);
351 	}
352 
353 	dynsize = gelf_fsize(elf, ELF_T_DYN, 1, EV_CURRENT);
354 	if (dynsize == 0) {
355 		warnx("%s: %s", fname, elf_errmsg(0));
356 		return (false);
357 	}
358 	count = len / dynsize;
359 
360 	memset(&src, 0, sizeof(src));
361 	src.d_buf = buf + offset;
362 	src.d_size = len;
363 	src.d_type = ELF_T_DYN;
364 	src.d_version = EV_CURRENT;
365 
366 	memset(&dst, 0, sizeof(dst));
367 	dst.d_buf = copy = malloc(count * sizeof(*dyn));
368 	dst.d_size = count * sizeof(*dyn);
369 	dst.d_type = ELF_T_DYN;
370 	dst.d_version = EV_CURRENT;
371 
372 	if (gelf_xlatetom(elf, &dst, &src, ehdr->e_ident[EI_DATA]) == NULL) {
373 		warnx("%s: failed to parse .dynamic: %s", fname, elf_errmsg(0));
374 		free(copy);
375 		return (false);
376 	}
377 
378 	dyn = copy;
379 	pie = false;
380 	for (i = 0; i < count; i++) {
381 		if (dyn[i].d_tag != DT_FLAGS_1)
382 			continue;
383 
384 		pie = (dyn[i].d_un.d_val & DF_1_PIE) != 0;
385 		break;
386 	}
387 
388 	free(copy);
389 	return (pie);
390 }
391 
392 static int
393 is_executable(const char *fname, int fd, int *is_shlib, int *type)
394 {
395 	Elf *elf;
396 	GElf_Ehdr ehdr;
397 	GElf_Phdr phdr;
398 	bool dynamic, freebsd, pie;
399 	int i;
400 
401 	*is_shlib = 0;
402 	*type = TYPE_UNKNOWN;
403 	dynamic = false;
404 	freebsd = false;
405 	pie = false;
406 
407 	if (elf_version(EV_CURRENT) == EV_NONE) {
408 		warnx("unsupported libelf");
409 		return (0);
410 	}
411 	elf = elf_begin(fd, ELF_C_READ, NULL);
412 	if (elf == NULL) {
413 		warnx("%s: %s", fname, elf_errmsg(0));
414 		return (0);
415 	}
416 	if (elf_kind(elf) != ELF_K_ELF) {
417 		elf_end(elf);
418 		warnx("%s: not a dynamic ELF executable", fname);
419 		return (0);
420 	}
421 	if (gelf_getehdr(elf, &ehdr) == NULL) {
422 		warnx("%s: %s", fname, elf_errmsg(0));
423 		elf_end(elf);
424 		return (0);
425 	}
426 
427 	*type = TYPE_ELF;
428 #if __ELF_WORD_SIZE > 32 && defined(ELF32_SUPPORTED)
429 	if (gelf_getclass(elf) == ELFCLASS32) {
430 		*type = TYPE_ELF32;
431 	}
432 #endif
433 
434 	freebsd = ehdr.e_ident[EI_OSABI] == ELFOSABI_FREEBSD;
435 	for (i = 0; i < ehdr.e_phnum; i++) {
436 		if (gelf_getphdr(elf, i, &phdr) == NULL) {
437 			warnx("%s: %s", fname, elf_errmsg(0));
438 			elf_end(elf);
439 			return (0);
440 		}
441 		switch (phdr.p_type) {
442 		case PT_NOTE:
443 			if (ehdr.e_ident[EI_OSABI] == ELFOSABI_NONE && !freebsd)
444 				freebsd = has_freebsd_abi_tag(fname, elf, &ehdr,
445 				    phdr.p_offset, phdr.p_filesz);
446 			break;
447 		case PT_DYNAMIC:
448 			dynamic = true;
449 			if (ehdr.e_type == ET_DYN)
450 				pie = is_pie(fname, elf, &ehdr, phdr.p_offset,
451 				    phdr.p_filesz);
452 			break;
453 		}
454 	}
455 
456 	if (!dynamic) {
457 		elf_end(elf);
458 		warnx("%s: not a dynamic ELF executable", fname);
459 		return (0);
460 	}
461 
462 	if (ehdr.e_type == ET_DYN && !pie) {
463 		*is_shlib = 1;
464 
465 		if (!freebsd) {
466 			elf_end(elf);
467 			warnx("%s: not a FreeBSD ELF shared object", fname);
468 			return (0);
469 		}
470 	}
471 
472 	elf_end(elf);
473 	return (1);
474 }
475