xref: /freebsd/sbin/ldconfig/ldconfig.c (revision f6a3b357e9be4c6423c85eff9a847163a0d307c8)
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 	if (rename(tmpfilename, hints_file) != 0) {
522 		warn("%s", hints_file);
523 		return -1;
524 	}
525 
526 	return 0;
527 }
528 
529 static int
530 readhints(void)
531 {
532 	int			fd;
533 	void			*addr;
534 	long			fsize;
535 	long			msize;
536 	struct hints_header	*hdr;
537 	struct hints_bucket	*blist;
538 	char			*strtab;
539 	struct shlib_list	*shp;
540 	int			i;
541 
542 	if ((fd = open(hints_file, O_RDONLY, 0)) == -1) {
543 		warn("%s", hints_file);
544 		return -1;
545 	}
546 
547 	msize = PAGE_SIZE;
548 	addr = mmap(0, msize, PROT_READ, MAP_PRIVATE, fd, 0);
549 
550 	if (addr == MAP_FAILED) {
551 		warn("%s", hints_file);
552 		return -1;
553 	}
554 
555 	hdr = (struct hints_header *)addr;
556 	if (HH_BADMAG(*hdr)) {
557 		warnx("%s: bad magic: %lo", hints_file,
558 			(unsigned long)hdr->hh_magic);
559 		return -1;
560 	}
561 
562 	if (hdr->hh_version != LD_HINTS_VERSION_1 &&
563 	    hdr->hh_version != LD_HINTS_VERSION_2) {
564 		warnx("unsupported version: %ld", (long)hdr->hh_version);
565 		return -1;
566 	}
567 
568 	if (hdr->hh_ehints > msize) {
569 		fsize = hdr->hh_ehints;
570 		munmap(addr, msize);
571 		addr = mmap(0, fsize, PROT_READ, MAP_PRIVATE, fd, 0);
572 		if (addr == MAP_FAILED) {
573 			warn("%s", hints_file);
574 			return -1;
575 		}
576 		hdr = (struct hints_header *)addr;
577 	}
578 	close(fd);
579 
580 	strtab = (char *)addr + hdr->hh_strtab;
581 
582 	if (hdr->hh_version >= LD_HINTS_VERSION_2)
583 		add_search_path(strtab + hdr->hh_dirlist);
584 	else if (rescan)
585 		errx(1, "%s too old and does not contain the search path",
586 			hints_file);
587 
588 	if (rescan)
589 		return 0;
590 
591 	blist = malloc(sizeof(*blist) * hdr->hh_nbucket);
592 	if (blist == NULL)
593 		err(1, "readhints");
594 	memcpy(blist, (char *)addr + hdr->hh_hashtab,
595 		sizeof(*blist) * hdr->hh_nbucket);
596 
597 
598 	for (i = 0; i < hdr->hh_nbucket; i++) {
599 		struct hints_bucket	*bp = &blist[i];
600 
601 		/* Sanity check */
602 		if (bp->hi_namex >= hdr->hh_strtab_sz) {
603 			warnx("bad name index: %#x", bp->hi_namex);
604 			free(blist);
605 			return -1;
606 		}
607 		if (bp->hi_pathx >= hdr->hh_strtab_sz) {
608 			warnx("bad path index: %#x", bp->hi_pathx);
609 			free(blist);
610 			return -1;
611 		}
612 
613 		/* Allocate new list element */
614 		shp = (struct shlib_list *)xmalloc(sizeof *shp);
615 		shp->name = strdup(strtab + bp->hi_namex);
616 		shp->path = strdup(strtab + bp->hi_pathx);
617 		bcopy(bp->hi_dewey, shp->dewey, sizeof(shp->dewey));
618 		shp->ndewey = bp->hi_ndewey;
619 		shp->next = NULL;
620 
621 		*shlib_tail = shp;
622 		shlib_tail = &shp->next;
623 	}
624 
625 	free(blist);
626 	return 0;
627 }
628 
629 static void
630 listhints(void)
631 {
632 	struct shlib_list	*shp;
633 	int			i;
634 
635 	printf("%s:\n", hints_file);
636 	printf("\tsearch directories: %s\n", dir_list);
637 
638 	for (i = 0, shp = shlib_head; shp; i++, shp = shp->next)
639 		printf("\t%d:-l%s.%d.%d => %s\n",
640 			i, shp->name, shp->major, shp->minor, shp->path);
641 
642 	return;
643 }
644