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