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