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