xref: /freebsd/usr.bin/ldd/ldd.c (revision ca8c576d10e22830d0c7ac865af21aad9ae44181)
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 aflag, c, fd, rval, status, is_shlib, rv, type;
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 		if ((fd = open(*argv, O_RDONLY, 0)) < 0) {
171 			warn("%s", *argv);
172 			rval |= 1;
173 			continue;
174 		}
175 		rv = is_executable(*argv, fd, &is_shlib, &type);
176 		close(fd);
177 		if (rv == 0) {
178 			rval |= 1;
179 			continue;
180 		}
181 
182 		switch (type) {
183 		case TYPE_ELF:
184 			break;
185 #if __ELF_WORD_SIZE > 32 && defined(ELF32_SUPPORTED)
186 		case TYPE_ELF32:
187 			rval |= execldd32(*argv, fmt1, fmt2, aflag);
188 			continue;
189 #endif
190 		case TYPE_UNKNOWN:
191 		default:
192 			/*
193 			 * This shouldn't happen unless is_executable()
194 			 * is broken.
195 			 */
196 			errx(EDOOFUS, "unknown executable type");
197 		}
198 
199 		/* ld.so magic */
200 		LDD_SETENV("TRACE_LOADED_OBJECTS", "yes", 1);
201 		if (fmt1 != NULL)
202 			LDD_SETENV("TRACE_LOADED_OBJECTS_FMT1", fmt1, 1);
203 		if (fmt2 != NULL)
204 			LDD_SETENV("TRACE_LOADED_OBJECTS_FMT2", fmt2, 1);
205 
206 		LDD_SETENV("TRACE_LOADED_OBJECTS_PROGNAME", *argv, 1);
207 		if (aflag)
208 			LDD_SETENV("TRACE_LOADED_OBJECTS_ALL", "1", 1);
209 		else if (fmt1 == NULL && fmt2 == NULL)
210 			/* Default formats */
211 			printf("%s:\n", *argv);
212 		fflush(stdout);
213 
214 		switch (fork()) {
215 		case -1:
216 			err(1, "fork");
217 			break;
218 		default:
219 			if (wait(&status) < 0) {
220 				warn("wait");
221 				rval |= 1;
222 			} else if (WIFSIGNALED(status)) {
223 				fprintf(stderr, "%s: signal %d\n", *argv,
224 				    WTERMSIG(status));
225 				rval |= 1;
226 			} else if (WIFEXITED(status) &&
227 			    WEXITSTATUS(status) != 0) {
228 				fprintf(stderr, "%s: exit status %d\n", *argv,
229 				    WEXITSTATUS(status));
230 				rval |= 1;
231 			}
232 			break;
233 		case 0:
234 			if (is_shlib == 0) {
235 				execl(*argv, *argv, (char *)NULL);
236 				warn("%s", *argv);
237 			} else {
238 				dlopen(*argv, RTLD_TRACE);
239 				warnx("%s: %s", *argv, dlerror());
240 			}
241 			_exit(1);
242 		}
243 	}
244 
245 	return (rval);
246 }
247 
248 static void
249 usage(void)
250 {
251 
252 	fprintf(stderr, "usage: ldd [-a] [-f format] program ...\n");
253 	exit(1);
254 }
255 
256 static bool
257 has_freebsd_abi_tag(const char *fname, Elf *elf, GElf_Ehdr *ehdr, off_t offset,
258     size_t len)
259 {
260 	Elf_Data dst, src;
261 	const Elf_Note *note;
262 	char *buf;
263 	const char *name;
264 	void *copy;
265 	size_t namesz, descsz;
266 	bool has_abi_tag;
267 
268 	buf = elf_rawfile(elf, NULL);
269 	if (buf == NULL) {
270 		warnx("%s: %s", fname, elf_errmsg(0));
271 		return (false);
272 	}
273 
274 	memset(&src, 0, sizeof(src));
275 	src.d_buf = buf + offset;
276 	src.d_size = len;
277 	src.d_type = ELF_T_NOTE;
278 	src.d_version = EV_CURRENT;
279 
280 	memset(&dst, 0, sizeof(dst));
281 	dst.d_buf = copy = malloc(len);
282 	dst.d_size = len;
283 	dst.d_type = ELF_T_NOTE;
284 	dst.d_version = EV_CURRENT;
285 
286 	if (gelf_xlatetom(elf, &dst, &src, ehdr->e_ident[EI_DATA]) == NULL) {
287 		warnx("%s: failed to parse notes: %s", fname, elf_errmsg(0));
288 		free(copy);
289 		return (false);
290 	}
291 
292 	buf = copy;
293 	has_abi_tag = false;
294 	for (;;) {
295 		if (len < sizeof(*note))
296 			break;
297 
298 		note = (const void *)buf;
299 		buf += sizeof(*note);
300 		len -= sizeof(*note);
301 
302 		namesz = roundup2(note->n_namesz, sizeof(uint32_t));
303 		descsz = roundup2(note->n_descsz, sizeof(uint32_t));
304 		if (len < namesz + descsz)
305 			break;
306 
307 		name = buf;
308 		if (note->n_namesz == sizeof(ELF_NOTE_FREEBSD) &&
309 		    strncmp(name, ELF_NOTE_FREEBSD, note->n_namesz) == 0 &&
310 		    note->n_type == NT_FREEBSD_ABI_TAG &&
311 		    note->n_descsz == sizeof(uint32_t)) {
312 			has_abi_tag = true;
313 			break;
314 		}
315 
316 		buf += namesz + descsz;
317 		len -= namesz + descsz;
318 	}
319 
320 	free(copy);
321 	return (has_abi_tag);
322 }
323 
324 static bool
325 is_pie(const char *fname, Elf *elf, GElf_Ehdr *ehdr, off_t offset, size_t len)
326 {
327 	Elf_Data dst, src;
328 	char *buf;
329 	void *copy;
330 	const GElf_Dyn *dyn;
331 	size_t dynsize;
332 	u_int count, i;
333 	bool pie;
334 
335 	buf = elf_rawfile(elf, NULL);
336 	if (buf == NULL) {
337 		warnx("%s: %s", fname, elf_errmsg(0));
338 		return (false);
339 	}
340 
341 	dynsize = gelf_fsize(elf, ELF_T_DYN, 1, EV_CURRENT);
342 	if (dynsize == 0) {
343 		warnx("%s: %s", fname, elf_errmsg(0));
344 		return (false);
345 	}
346 	count = len / dynsize;
347 
348 	memset(&src, 0, sizeof(src));
349 	src.d_buf = buf + offset;
350 	src.d_size = len;
351 	src.d_type = ELF_T_DYN;
352 	src.d_version = EV_CURRENT;
353 
354 	memset(&dst, 0, sizeof(dst));
355 	dst.d_buf = copy = malloc(count * sizeof(*dyn));
356 	dst.d_size = count * sizeof(*dyn);
357 	dst.d_type = ELF_T_DYN;
358 	dst.d_version = EV_CURRENT;
359 
360 	if (gelf_xlatetom(elf, &dst, &src, ehdr->e_ident[EI_DATA]) == NULL) {
361 		warnx("%s: failed to parse .dynamic: %s", fname, elf_errmsg(0));
362 		free(copy);
363 		return (false);
364 	}
365 
366 	dyn = copy;
367 	pie = false;
368 	for (i = 0; i < count; i++) {
369 		if (dyn[i].d_tag != DT_FLAGS_1)
370 			continue;
371 
372 		pie = (dyn[i].d_un.d_val & DF_1_PIE) != 0;
373 		break;
374 	}
375 
376 	free(copy);
377 	return (pie);
378 }
379 
380 static int
381 is_executable(const char *fname, int fd, int *is_shlib, int *type)
382 {
383 	Elf *elf;
384 	GElf_Ehdr ehdr;
385 	GElf_Phdr phdr;
386 	bool dynamic, freebsd, pie;
387 	int i;
388 
389 	*is_shlib = 0;
390 	*type = TYPE_UNKNOWN;
391 	dynamic = false;
392 	freebsd = false;
393 	pie = false;
394 
395 	if (elf_version(EV_CURRENT) == EV_NONE) {
396 		warnx("unsupported libelf");
397 		return (0);
398 	}
399 	elf = elf_begin(fd, ELF_C_READ, NULL);
400 	if (elf == NULL) {
401 		warnx("%s: %s", fname, elf_errmsg(0));
402 		return (0);
403 	}
404 	if (elf_kind(elf) != ELF_K_ELF) {
405 		elf_end(elf);
406 		warnx("%s: not a dynamic ELF executable", fname);
407 		return (0);
408 	}
409 	if (gelf_getehdr(elf, &ehdr) == NULL) {
410 		warnx("%s: %s", fname, elf_errmsg(0));
411 		elf_end(elf);
412 		return (0);
413 	}
414 
415 	*type = TYPE_ELF;
416 #if __ELF_WORD_SIZE > 32 && defined(ELF32_SUPPORTED)
417 	if (gelf_getclass(elf) == ELFCLASS32) {
418 		*type = TYPE_ELF32;
419 	}
420 #endif
421 
422 	freebsd = ehdr.e_ident[EI_OSABI] == ELFOSABI_FREEBSD;
423 	for (i = 0; i < ehdr.e_phnum; i++) {
424 		if (gelf_getphdr(elf, i, &phdr) == NULL) {
425 			warnx("%s: %s", fname, elf_errmsg(0));
426 			elf_end(elf);
427 			return (0);
428 		}
429 		switch (phdr.p_type) {
430 		case PT_NOTE:
431 			if (ehdr.e_ident[EI_OSABI] == ELFOSABI_NONE && !freebsd)
432 				freebsd = has_freebsd_abi_tag(fname, elf, &ehdr,
433 				    phdr.p_offset, phdr.p_filesz);
434 			break;
435 		case PT_DYNAMIC:
436 			dynamic = true;
437 			if (ehdr.e_type == ET_DYN)
438 				pie = is_pie(fname, elf, &ehdr, phdr.p_offset,
439 				    phdr.p_filesz);
440 			break;
441 		}
442 	}
443 
444 	if (!dynamic) {
445 		elf_end(elf);
446 		warnx("%s: not a dynamic ELF executable", fname);
447 		return (0);
448 	}
449 
450 	if (ehdr.e_type == ET_DYN && !pie) {
451 		*is_shlib = 1;
452 
453 		if (!freebsd) {
454 			elf_end(elf);
455 			warnx("%s: not a FreeBSD ELF shared object", fname);
456 			return (0);
457 		}
458 	}
459 
460 	elf_end(elf);
461 	return (1);
462 }
463