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