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