xref: /freebsd/sbin/ldconfig/ldconfig.c (revision f39bffc62c1395bde25d152c7f68fdf7cbaab414)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1993,1995 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 #ifndef lint
34 static const char rcsid[] =
35   "$FreeBSD$";
36 #endif /* not lint */
37 
38 #include <sys/param.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <sys/mman.h>
42 #include <a.out.h>
43 #include <ctype.h>
44 #include <dirent.h>
45 #include <elf-hints.h>
46 #include <err.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <sys/link_aout.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 
55 #include "ldconfig.h"
56 #include "shlib.h"
57 #include "support.h"
58 
59 #if DEBUG
60 /* test */
61 #undef _PATH_LD_HINTS
62 #define _PATH_LD_HINTS		"./ld.so.hints"
63 #undef _PATH_ELF_HINTS
64 #define _PATH_ELF_HINTS		"./ld-elf.so.hints"
65 #endif
66 
67 #define	_PATH_LD32_HINTS	"/var/run/ld32.so.hints"
68 #define	_PATH_ELF32_HINTS	"/var/run/ld-elf32.so.hints"
69 #define	_PATH_ELFSOFT_HINTS	"/var/run/ld-elf-soft.so.hints"
70 
71 #undef major
72 #undef minor
73 
74 static int			verbose;
75 static int			nostd;
76 static int			justread;
77 static int			merge;
78 static int			rescan;
79 static const char		*hints_file;
80 
81 struct shlib_list {
82 	/* Internal list of shared libraries found */
83 	char			*name;
84 	char			*path;
85 	int			dewey[MAXDEWEY];
86 	int			ndewey;
87 #define major dewey[0]
88 #define minor dewey[1]
89 	struct shlib_list	*next;
90 };
91 
92 static struct shlib_list	*shlib_head = NULL, **shlib_tail = &shlib_head;
93 static char			*dir_list;
94 
95 static int		buildhints(void);
96 static int		dodir(char *, int);
97 int			dofile(char *, int);
98 static void		enter(char *, char *, char *, int *, int);
99 static void		listhints(void);
100 static int		readhints(void);
101 static void		usage(void);
102 
103 /*
104  * Note on aout/a.out support.
105  * To properly support shared libraries for compat2x, which are a.out, we need
106  * to support a.out here.  As of 2013, bug reports are still coming in for this
107  * feature (on amd64 no less), so we know it is still in use.
108  */
109 
110 int
111 main(int argc, char **argv)
112 {
113 	int		i, c;
114 	int		rval = 0;
115 	int		is_aout = 0;
116 	int		is_32 = 0;
117 	int		is_soft = 0;
118 
119 	while (argc > 1) {
120 		if (strcmp(argv[1], "-aout") == 0) {
121 			is_aout = 1;
122 			argc--;
123 			argv++;
124 		} else if (strcmp(argv[1], "-elf") == 0) {
125 			is_aout = 0;
126 			argc--;
127 			argv++;
128 		} else if (strcmp(argv[1], "-32") == 0) {
129 			is_32 = 1;
130 			argc--;
131 			argv++;
132 		} else if (strcmp(argv[1], "-soft") == 0) {
133 			is_soft = 1;
134 			argc--;
135 			argv++;
136 		} else {
137 			break;
138 		}
139 	}
140 
141 	if (is_soft)
142 		hints_file = _PATH_ELFSOFT_HINTS;	/* Never will have a.out softfloat */
143 	else if (is_32)
144 		hints_file = is_aout ? _PATH_LD32_HINTS : _PATH_ELF32_HINTS;
145 	else
146 		hints_file = is_aout ? _PATH_LD_HINTS : _PATH_ELF_HINTS;
147 	if (argc == 1)
148 		rescan = 1;
149 	else while((c = getopt(argc, argv, "Rf:imrsv")) != -1) {
150 		switch (c) {
151 		case 'R':
152 			rescan = 1;
153 			break;
154 		case 'f':
155 			hints_file = optarg;
156 			break;
157 		case 'i':
158 			insecure = 1;
159 			break;
160 		case 'm':
161 			merge = 1;
162 			break;
163 		case 'r':
164 			justread = 1;
165 			break;
166 		case 's':
167 			nostd = 1;
168 			break;
169 		case 'v':
170 			verbose = 1;
171 			break;
172 		default:
173 			usage();
174 			break;
175 		}
176 	}
177 
178 	if (!is_aout) {
179 		if (justread)
180 			list_elf_hints(hints_file);
181 		else
182 			update_elf_hints(hints_file, argc - optind,
183 			    argv + optind, merge || rescan);
184 		return 0;
185 	}
186 
187 	/* Here begins the aout libs processing */
188 	dir_list = strdup("");
189 
190 	if (justread || merge || rescan) {
191 		if ((rval = readhints()) != 0)
192 			return rval;
193 	}
194 
195 	if (!nostd && !merge && !rescan)
196 		std_search_path();
197 
198 	/* Add any directories/files from the command line */
199 	if (!justread) {
200 		for (i = optind; i < argc; i++) {
201 			struct stat stbuf;
202 
203 			if (stat(argv[i], &stbuf) == -1) {
204 				warn("%s", argv[i]);
205 				rval = -1;
206 			} else if (strcmp(argv[i], "/usr/lib") == 0) {
207 				warnx("WARNING! '%s' can not be used", argv[i]);
208 				rval = -1;
209 			} else {
210 				/*
211 				 * See if this is a directory-containing
212 				 * file instead of a directory
213 				 */
214 				if (S_ISREG(stbuf.st_mode))
215 					rval |= dofile(argv[i], 0);
216 				else
217 					add_search_path(argv[i]);
218 			}
219 		}
220 	}
221 
222 	for (i = 0; i < n_search_dirs; i++) {
223 		char *cp = concat(dir_list, *dir_list?":":"", search_dirs[i]);
224 		free(dir_list);
225 		dir_list = cp;
226 	}
227 
228 	if (justread) {
229 		listhints();
230 		return 0;
231 	}
232 
233 	for (i = 0; i < n_search_dirs; i++)
234 		rval |= dodir(search_dirs[i], 1);
235 
236 	rval |= buildhints();
237 
238 	return rval;
239 }
240 
241 static void
242 usage(void)
243 {
244 	fprintf(stderr,
245 	"usage: ldconfig [-32] [-aout | -elf] [-Rimrsv] [-f hints_file] [directory | file ...]\n");
246 	exit(1);
247 }
248 
249 int
250 dofile(char *fname, int silent)
251 {
252 	FILE *hfp;
253 	char buf[MAXPATHLEN];
254 	int rval = 0;
255 	char *cp, *sp;
256 
257 	if ((hfp = fopen(fname, "r")) == NULL) {
258 		warn("%s", fname);
259 		return -1;
260 	}
261 
262 	while (fgets(buf, sizeof(buf), hfp)) {
263 		cp = buf;
264 		while (isspace(*cp))
265 			cp++;
266 		if (*cp == '#' || *cp == '\0')
267 			continue;
268 		sp = cp;
269 		while (!isspace(*cp) && *cp != '\0')
270 			cp++;
271 
272 		if (*cp != '\n') {
273 			*cp = '\0';
274 			warnx("%s: trailing characters ignored", sp);
275 		}
276 
277 		*cp = '\0';
278 
279 		rval |= dodir(sp, silent);
280 	}
281 
282 	(void)fclose(hfp);
283 	return rval;
284 }
285 
286 int
287 dodir(char *dir, int silent)
288 {
289 	DIR		*dd;
290 	struct dirent	*dp;
291 	char		name[MAXPATHLEN];
292 	int		dewey[MAXDEWEY], ndewey;
293 
294 	if ((dd = opendir(dir)) == NULL) {
295 		if (silent && errno == ENOENT)	/* Ignore the error */
296 			return 0;
297 		warn("%s", dir);
298 		return -1;
299 	}
300 
301 	while ((dp = readdir(dd)) != NULL) {
302 		int n;
303 		char *cp;
304 
305 		/* Check for `lib' prefix */
306 		if (dp->d_name[0] != 'l' ||
307 		    dp->d_name[1] != 'i' ||
308 		    dp->d_name[2] != 'b')
309 			continue;
310 
311 		/* Copy the entry minus prefix */
312 		(void)strcpy(name, dp->d_name + 3);
313 		n = strlen(name);
314 		if (n < 4)
315 			continue;
316 
317 		/* Find ".so." in name */
318 		for (cp = name + n - 4; cp > name; --cp) {
319 			if (cp[0] == '.' &&
320 			    cp[1] == 's' &&
321 			    cp[2] == 'o' &&
322 			    cp[3] == '.')
323 				break;
324 		}
325 		if (cp <= name)
326 			continue;
327 
328 		*cp = '\0';
329 		if (!isdigit(*(cp+4)))
330 			continue;
331 
332 		bzero((caddr_t)dewey, sizeof(dewey));
333 		ndewey = getdewey(dewey, cp + 4);
334 		if (ndewey < 2)
335 			continue;
336 		enter(dir, dp->d_name, name, dewey, ndewey);
337 	}
338 
339 	closedir(dd);
340 	return 0;
341 }
342 
343 static void
344 enter(char *dir, char *file, char *name, int dewey[], int ndewey)
345 {
346 	struct shlib_list	*shp;
347 
348 	for (shp = shlib_head; shp; shp = shp->next) {
349 		if (strcmp(name, shp->name) != 0 || major != shp->major)
350 			continue;
351 
352 		/* Name matches existing entry */
353 		if (cmpndewey(dewey, ndewey, shp->dewey, shp->ndewey) > 0) {
354 
355 			/* Update this entry with higher versioned lib */
356 			if (verbose)
357 				printf("Updating lib%s.%d.%d to %s/%s\n",
358 					shp->name, shp->major, shp->minor,
359 					dir, file);
360 
361 			free(shp->name);
362 			shp->name = strdup(name);
363 			free(shp->path);
364 			shp->path = concat(dir, "/", file);
365 			bcopy(dewey, shp->dewey, sizeof(shp->dewey));
366 			shp->ndewey = ndewey;
367 		}
368 		break;
369 	}
370 
371 	if (shp)
372 		/* Name exists: older version or just updated */
373 		return;
374 
375 	/* Allocate new list element */
376 	if (verbose)
377 		printf("Adding %s/%s\n", dir, file);
378 
379 	shp = (struct shlib_list *)xmalloc(sizeof *shp);
380 	shp->name = strdup(name);
381 	shp->path = concat(dir, "/", file);
382 	bcopy(dewey, shp->dewey, sizeof(shp->dewey));
383 	shp->ndewey = ndewey;
384 	shp->next = NULL;
385 
386 	*shlib_tail = shp;
387 	shlib_tail = &shp->next;
388 }
389 
390 
391 static int
392 hinthash(char *cp, int vmajor)
393 {
394 	int	k = 0;
395 
396 	while (*cp)
397 		k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;
398 
399 	k = (((k << 1) + (k >> 14)) ^ (vmajor*257)) & 0x3fff;
400 
401 	return k;
402 }
403 
404 int
405 buildhints(void)
406 {
407 	struct hints_header	hdr;
408 	struct hints_bucket	*blist;
409 	struct shlib_list	*shp;
410 	char			*strtab;
411 	int			i, n, str_index = 0;
412 	int			strtab_sz = 0;	/* Total length of strings */
413 	int			nhints = 0;	/* Total number of hints */
414 	int			fd;
415 	char			*tmpfilename;
416 
417 	for (shp = shlib_head; shp; shp = shp->next) {
418 		strtab_sz += 1 + strlen(shp->name);
419 		strtab_sz += 1 + strlen(shp->path);
420 		nhints++;
421 	}
422 
423 	/* Fill hints file header */
424 	hdr.hh_magic = HH_MAGIC;
425 	hdr.hh_version = LD_HINTS_VERSION_2;
426 	hdr.hh_nbucket = 1 * nhints;
427 	n = hdr.hh_nbucket * sizeof(struct hints_bucket);
428 	hdr.hh_hashtab = sizeof(struct hints_header);
429 	hdr.hh_strtab = hdr.hh_hashtab + n;
430 	hdr.hh_dirlist = strtab_sz;
431 	strtab_sz += 1 + strlen(dir_list);
432 	hdr.hh_strtab_sz = strtab_sz;
433 	hdr.hh_ehints = hdr.hh_strtab + hdr.hh_strtab_sz;
434 
435 	if (verbose)
436 		printf("Totals: entries %d, buckets %ld, string size %d\n",
437 			nhints, (long)hdr.hh_nbucket, strtab_sz);
438 
439 	/* Allocate buckets and string table */
440 	blist = (struct hints_bucket *)xmalloc(n);
441 	bzero((char *)blist, n);
442 	for (i = 0; i < hdr.hh_nbucket; i++)
443 		/* Empty all buckets */
444 		blist[i].hi_next = -1;
445 
446 	strtab = (char *)xmalloc(strtab_sz);
447 
448 	/* Enter all */
449 	for (shp = shlib_head; shp; shp = shp->next) {
450 		struct hints_bucket	*bp;
451 
452 		bp = blist +
453 		  (hinthash(shp->name, shp->major) % hdr.hh_nbucket);
454 
455 		if (bp->hi_pathx) {
456 			int	j;
457 
458 			for (j = 0; j < hdr.hh_nbucket; j++) {
459 				if (blist[j].hi_pathx == 0)
460 					break;
461 			}
462 			if (j == hdr.hh_nbucket) {
463 				warnx("bummer!");
464 				return -1;
465 			}
466 			while (bp->hi_next != -1)
467 				bp = &blist[bp->hi_next];
468 			bp->hi_next = j;
469 			bp = blist + j;
470 		}
471 
472 		/* Insert strings in string table */
473 		bp->hi_namex = str_index;
474 		strcpy(strtab + str_index, shp->name);
475 		str_index += 1 + strlen(shp->name);
476 
477 		bp->hi_pathx = str_index;
478 		strcpy(strtab + str_index, shp->path);
479 		str_index += 1 + strlen(shp->path);
480 
481 		/* Copy versions */
482 		bcopy(shp->dewey, bp->hi_dewey, sizeof(bp->hi_dewey));
483 		bp->hi_ndewey = shp->ndewey;
484 	}
485 
486 	/* Copy search directories */
487 	strcpy(strtab + str_index, dir_list);
488 	str_index += 1 + strlen(dir_list);
489 
490 	/* Sanity check */
491 	if (str_index != strtab_sz) {
492 		errx(1, "str_index(%d) != strtab_sz(%d)", str_index, strtab_sz);
493 	}
494 
495 	tmpfilename = concat(hints_file, ".XXXXXXXXXX", "");
496 	umask(0);	/* Create with exact permissions */
497 	if ((fd = mkstemp(tmpfilename)) == -1) {
498 		warn("%s", tmpfilename);
499 		return -1;
500 	}
501 	fchmod(fd, 0444);
502 
503 	if (write(fd, &hdr, sizeof(struct hints_header)) !=
504 						sizeof(struct hints_header)) {
505 		warn("%s", hints_file);
506 		return -1;
507 	}
508 	if (write(fd, blist, hdr.hh_nbucket * sizeof(*blist)) !=
509 				(ssize_t)(hdr.hh_nbucket * sizeof(*blist))) {
510 		warn("%s", hints_file);
511 		return -1;
512 	}
513 	if (write(fd, strtab, strtab_sz) != strtab_sz) {
514 		warn("%s", hints_file);
515 		return -1;
516 	}
517 	if (close(fd) != 0) {
518 		warn("%s", hints_file);
519 		return -1;
520 	}
521 
522 	/* Install it */
523 	if (unlink(hints_file) != 0 && errno != ENOENT) {
524 		warn("%s", hints_file);
525 		return -1;
526 	}
527 
528 	if (rename(tmpfilename, hints_file) != 0) {
529 		warn("%s", hints_file);
530 		return -1;
531 	}
532 
533 	return 0;
534 }
535 
536 static int
537 readhints(void)
538 {
539 	int			fd;
540 	void			*addr;
541 	long			fsize;
542 	long			msize;
543 	struct hints_header	*hdr;
544 	struct hints_bucket	*blist;
545 	char			*strtab;
546 	struct shlib_list	*shp;
547 	int			i;
548 
549 	if ((fd = open(hints_file, O_RDONLY, 0)) == -1) {
550 		warn("%s", hints_file);
551 		return -1;
552 	}
553 
554 	msize = PAGE_SIZE;
555 	addr = mmap(0, msize, PROT_READ, MAP_PRIVATE, fd, 0);
556 
557 	if (addr == MAP_FAILED) {
558 		warn("%s", hints_file);
559 		return -1;
560 	}
561 
562 	hdr = (struct hints_header *)addr;
563 	if (HH_BADMAG(*hdr)) {
564 		warnx("%s: bad magic: %lo", hints_file,
565 			(unsigned long)hdr->hh_magic);
566 		return -1;
567 	}
568 
569 	if (hdr->hh_version != LD_HINTS_VERSION_1 &&
570 	    hdr->hh_version != LD_HINTS_VERSION_2) {
571 		warnx("unsupported version: %ld", (long)hdr->hh_version);
572 		return -1;
573 	}
574 
575 	if (hdr->hh_ehints > msize) {
576 		fsize = hdr->hh_ehints;
577 		munmap(addr, msize);
578 		addr = mmap(0, fsize, PROT_READ, MAP_PRIVATE, fd, 0);
579 		if (addr == MAP_FAILED) {
580 			warn("%s", hints_file);
581 			return -1;
582 		}
583 		hdr = (struct hints_header *)addr;
584 	}
585 	close(fd);
586 
587 	strtab = (char *)addr + hdr->hh_strtab;
588 
589 	if (hdr->hh_version >= LD_HINTS_VERSION_2)
590 		add_search_path(strtab + hdr->hh_dirlist);
591 	else if (rescan)
592 		errx(1, "%s too old and does not contain the search path",
593 			hints_file);
594 
595 	if (rescan)
596 		return 0;
597 
598 	blist = malloc(sizeof(*blist) * hdr->hh_nbucket);
599 	if (blist == NULL)
600 		err(1, "readhints");
601 	memcpy(blist, (char *)addr + hdr->hh_hashtab,
602 		sizeof(*blist) * hdr->hh_nbucket);
603 
604 
605 	for (i = 0; i < hdr->hh_nbucket; i++) {
606 		struct hints_bucket	*bp = &blist[i];
607 
608 		/* Sanity check */
609 		if (bp->hi_namex >= hdr->hh_strtab_sz) {
610 			warnx("bad name index: %#x", bp->hi_namex);
611 			free(blist);
612 			return -1;
613 		}
614 		if (bp->hi_pathx >= hdr->hh_strtab_sz) {
615 			warnx("bad path index: %#x", bp->hi_pathx);
616 			free(blist);
617 			return -1;
618 		}
619 
620 		/* Allocate new list element */
621 		shp = (struct shlib_list *)xmalloc(sizeof *shp);
622 		shp->name = strdup(strtab + bp->hi_namex);
623 		shp->path = strdup(strtab + bp->hi_pathx);
624 		bcopy(bp->hi_dewey, shp->dewey, sizeof(shp->dewey));
625 		shp->ndewey = bp->hi_ndewey;
626 		shp->next = NULL;
627 
628 		*shlib_tail = shp;
629 		shlib_tail = &shp->next;
630 	}
631 
632 	free(blist);
633 	return 0;
634 }
635 
636 static void
637 listhints(void)
638 {
639 	struct shlib_list	*shp;
640 	int			i;
641 
642 	printf("%s:\n", hints_file);
643 	printf("\tsearch directories: %s\n", dir_list);
644 
645 	for (i = 0, shp = shlib_head; shp; i++, shp = shp->next)
646 		printf("\t%d:-l%s.%d.%d => %s\n",
647 			i, shp->name, shp->major, shp->minor, shp->path);
648 
649 	return;
650 }
651