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