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