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