elfhints.c revision 63872
1/*-
2 * Copyright (c) 1998 John D. Polstra
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 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 *
26 * $FreeBSD: head/sbin/ldconfig/elfhints.c 63872 2000-07-26 04:47:17Z jdp $
27 */
28
29#include <sys/param.h>
30#include <sys/mman.h>
31#include <sys/stat.h>
32
33#include <ctype.h>
34#include <dirent.h>
35#include <elf.h>
36#include <err.h>
37#include <errno.h>
38#include <fcntl.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#include <unistd.h>
43
44#include "ldconfig.h"
45
46#define MAXDIRS		1024		/* Maximum directories in path */
47#define MAXFILESIZE	(16*1024)	/* Maximum hints file size */
48
49static void	add_dir(const char *, const char *);
50static void	read_dirs_from_file(const char *, const char *);
51static void	read_elf_hints(const char *, int);
52static void	write_elf_hints(const char *);
53
54static const char	*dirs[MAXDIRS];
55static int		 ndirs;
56
57static void
58add_dir(const char *hintsfile, const char *name)
59{
60	struct stat 	stbuf;
61	int		i;
62
63	/* Do some security checks */
64	if (stat(name, &stbuf) == -1) {
65		warn("%s", name);
66		return;
67	}
68	if (stbuf.st_uid != 0) {
69		warnx("%s: not owned by root", name);
70		return;
71	}
72	if ((stbuf.st_mode & S_IWOTH) != 0) {
73		warnx("%s: ignoring world-writable directory", name);
74        	return;
75	}
76
77	for (i = 0;  i < ndirs;  i++)
78		if (strcmp(dirs[i], name) == 0)
79			return;
80	if (ndirs >= MAXDIRS)
81		errx(1, "\"%s\": Too many directories in path", hintsfile);
82	dirs[ndirs++] = name;
83}
84
85void
86list_elf_hints(const char *hintsfile)
87{
88	int	i;
89	int	nlibs;
90
91	read_elf_hints(hintsfile, 1);
92	printf("%s:\n", hintsfile);
93	printf("\tsearch directories:");
94	for (i = 0;  i < ndirs;  i++)
95		printf("%c%s", i == 0 ? ' ' : ':', dirs[i]);
96	printf("\n");
97
98	nlibs = 0;
99	for (i = 0;  i < ndirs;  i++) {
100		DIR		*dirp;
101		struct dirent	*dp;
102
103		if ((dirp = opendir(dirs[i])) == NULL)
104			continue;
105		while ((dp = readdir(dirp)) != NULL) {
106			int		 len;
107			int		 namelen;
108			const char	*name;
109			const char	*vers;
110
111			/* Name can't be shorter than "libx.so.0" */
112			if ((len = strlen(dp->d_name)) < 9 ||
113			    strncmp(dp->d_name, "lib", 3) != 0)
114				continue;
115			name = dp->d_name + 3;
116			vers = dp->d_name + len;
117			while (vers > dp->d_name && isdigit(*(vers-1)))
118				vers--;
119			if (vers == dp->d_name + len)
120				continue;
121			if (vers < dp->d_name + 4 ||
122			    strncmp(vers - 4, ".so.", 4) != 0)
123				continue;
124
125			/* We have a valid shared library name. */
126			namelen = (vers - 4) - name;
127			printf("\t%d:-l%.*s.%s => %s/%s\n", nlibs,
128			    namelen, name, vers, dirs[i], dp->d_name);
129			nlibs++;
130		}
131		closedir(dirp);
132	}
133}
134
135static void
136read_dirs_from_file(const char *hintsfile, const char *listfile)
137{
138	FILE	*fp;
139	char	 buf[MAXPATHLEN];
140	int	 linenum;
141
142	if ((fp = fopen(listfile, "r")) == NULL)
143		err(1, "%s", listfile);
144
145	linenum = 0;
146	while (fgets(buf, sizeof buf, fp) != NULL) {
147		char	*cp, *sp;
148
149		linenum++;
150		cp = buf;
151		/* Skip leading white space. */
152		while (isspace(*cp))
153			cp++;
154		if (*cp == '#' || *cp == '\0')
155			continue;
156		sp = cp;
157		/* Advance over the directory name. */
158		while (!isspace(*cp) && *cp != '\0')
159			cp++;
160		/* Terminate the string and skip trailing white space. */
161		if (*cp != '\0') {
162			*cp++ = '\0';
163			while (isspace(*cp))
164				cp++;
165		}
166		/* Now we had better be at the end of the line. */
167		if (*cp != '\0')
168			warnx("%s:%d: trailing characters ignored",
169			    listfile, linenum);
170
171		if ((sp = strdup(sp)) == NULL)
172			errx(1, "Out of memory");
173		add_dir(hintsfile, sp);
174	}
175
176	fclose(fp);
177}
178
179static void
180read_elf_hints(const char *hintsfile, int must_exist)
181{
182	int	 		 fd;
183	struct stat		 s;
184	void			*mapbase;
185	struct elfhints_hdr	*hdr;
186	char			*strtab;
187	char			*dirlist;
188	char			*p;
189
190	if ((fd = open(hintsfile, O_RDONLY)) == -1) {
191		if (errno == ENOENT && !must_exist)
192			return;
193		err(1, "Cannot open \"%s\"", hintsfile);
194	}
195	if (fstat(fd, &s) == -1)
196		err(1, "Cannot stat \"%s\"", hintsfile);
197	if (s.st_size > MAXFILESIZE)
198		errx(1, "\"%s\" is unreasonably large", hintsfile);
199	/*
200	 * We use a read-write, private mapping so that we can null-terminate
201	 * some strings in it without affecting the underlying file.
202	 */
203	mapbase = mmap(NULL, s.st_size, PROT_READ|PROT_WRITE,
204	    MAP_PRIVATE, fd, 0);
205	if (mapbase == MAP_FAILED)
206		err(1, "Cannot mmap \"%s\"", hintsfile);
207	close(fd);
208
209	hdr = (struct elfhints_hdr *)mapbase;
210	if (hdr->magic != ELFHINTS_MAGIC)
211		errx(1, "\"%s\": invalid file format", hintsfile);
212	if (hdr->version != 1)
213		errx(1, "\"%s\": unrecognized file version (%d)", hintsfile,
214		    hdr->version);
215
216	strtab = (char *)mapbase + hdr->strtab;
217	dirlist = strtab + hdr->dirlist;
218
219	if (*dirlist != '\0')
220		while ((p = strsep(&dirlist, ":")) != NULL)
221			add_dir(hintsfile, p);
222}
223
224void
225update_elf_hints(const char *hintsfile, int argc, char **argv, int merge)
226{
227	int	i;
228
229	if (merge)
230		read_elf_hints(hintsfile, 0);
231	for (i = 0;  i < argc;  i++) {
232		struct stat	s;
233
234		if (stat(argv[i], &s) == -1)
235			warn("warning: %s", argv[i]);
236		else if (S_ISREG(s.st_mode))
237			read_dirs_from_file(hintsfile, argv[i]);
238		else
239			add_dir(hintsfile, argv[i]);
240	}
241	write_elf_hints(hintsfile);
242}
243
244static void
245write_elf_hints(const char *hintsfile)
246{
247	struct elfhints_hdr	 hdr;
248	char			*tempname;
249	int			 fd;
250	FILE			*fp;
251	int			 i;
252
253	if (asprintf(&tempname, "%s.XXXXXX", hintsfile) == -1)
254		errx(1, "Out of memory");
255	if ((fd = mkstemp(tempname)) ==  -1)
256		err(1, "mkstemp(%s)", tempname);
257	if (fchmod(fd, 0444) == -1)
258		err(1, "fchmod(%s)", tempname);
259	if ((fp = fdopen(fd, "wb")) == NULL)
260		err(1, "fdopen(%s)", tempname);
261
262	hdr.magic = ELFHINTS_MAGIC;
263	hdr.version = 1;
264	hdr.strtab = sizeof hdr;
265	hdr.strsize = 0;
266	hdr.dirlist = 0;
267	memset(hdr.spare, 0, sizeof hdr.spare);
268
269	/* Count up the size of the string table. */
270	if (ndirs > 0) {
271		hdr.strsize += strlen(dirs[0]);
272		for (i = 1;  i < ndirs;  i++)
273			hdr.strsize += 1 + strlen(dirs[i]);
274	}
275	hdr.dirlistlen = hdr.strsize;
276	hdr.strsize++;	/* For the null terminator */
277
278	/* Write the header. */
279	if (fwrite(&hdr, 1, sizeof hdr, fp) != sizeof hdr)
280		err(1, "%s: write error", tempname);
281	/* Write the strings. */
282	if (ndirs > 0) {
283		if (fputs(dirs[0], fp) == EOF)
284			err(1, "%s: write error", tempname);
285		for (i = 1;  i < ndirs;  i++)
286			if (fprintf(fp, ":%s", dirs[i]) < 0)
287				err(1, "%s: write error", tempname);
288	}
289	if (putc('\0', fp) == EOF || fclose(fp) == EOF)
290		err(1, "%s: write error", tempname);
291
292	if (rename(tempname, hintsfile) == -1)
293		err(1, "rename %s to %s", tempname, hintsfile);
294	free(tempname);
295}
296