xref: /linux/scripts/basic/fixdep.c (revision ec63e2a4897075e427c121d863bd89c44578094f)
1 /*
2  * "Optimize" a list of dependencies as spit out by gcc -MD
3  * for the kernel build
4  * ===========================================================================
5  *
6  * Author       Kai Germaschewski
7  * Copyright    2002 by Kai Germaschewski  <kai.germaschewski@gmx.de>
8  *
9  * This software may be used and distributed according to the terms
10  * of the GNU General Public License, incorporated herein by reference.
11  *
12  *
13  * Introduction:
14  *
15  * gcc produces a very nice and correct list of dependencies which
16  * tells make when to remake a file.
17  *
18  * To use this list as-is however has the drawback that virtually
19  * every file in the kernel includes autoconf.h.
20  *
21  * If the user re-runs make *config, autoconf.h will be
22  * regenerated.  make notices that and will rebuild every file which
23  * includes autoconf.h, i.e. basically all files. This is extremely
24  * annoying if the user just changed CONFIG_HIS_DRIVER from n to m.
25  *
26  * So we play the same trick that "mkdep" played before. We replace
27  * the dependency on autoconf.h by a dependency on every config
28  * option which is mentioned in any of the listed prerequisites.
29  *
30  * kconfig populates a tree in include/config/ with an empty file
31  * for each config symbol and when the configuration is updated
32  * the files representing changed config options are touched
33  * which then let make pick up the changes and the files that use
34  * the config symbols are rebuilt.
35  *
36  * So if the user changes his CONFIG_HIS_DRIVER option, only the objects
37  * which depend on "include/config/his/driver.h" will be rebuilt,
38  * so most likely only his driver ;-)
39  *
40  * The idea above dates, by the way, back to Michael E Chastain, AFAIK.
41  *
42  * So to get dependencies right, there are two issues:
43  * o if any of the files the compiler read changed, we need to rebuild
44  * o if the command line given to the compile the file changed, we
45  *   better rebuild as well.
46  *
47  * The former is handled by using the -MD output, the later by saving
48  * the command line used to compile the old object and comparing it
49  * to the one we would now use.
50  *
51  * Again, also this idea is pretty old and has been discussed on
52  * kbuild-devel a long time ago. I don't have a sensibly working
53  * internet connection right now, so I rather don't mention names
54  * without double checking.
55  *
56  * This code here has been based partially based on mkdep.c, which
57  * says the following about its history:
58  *
59  *   Copyright abandoned, Michael Chastain, <mailto:mec@shout.net>.
60  *   This is a C version of syncdep.pl by Werner Almesberger.
61  *
62  *
63  * It is invoked as
64  *
65  *   fixdep <depfile> <target> <cmdline>
66  *
67  * and will read the dependency file <depfile>
68  *
69  * The transformed dependency snipped is written to stdout.
70  *
71  * It first generates a line
72  *
73  *   cmd_<target> = <cmdline>
74  *
75  * and then basically copies the .<target>.d file to stdout, in the
76  * process filtering out the dependency on autoconf.h and adding
77  * dependencies on include/config/my/option.h for every
78  * CONFIG_MY_OPTION encountered in any of the prerequisites.
79  *
80  * It will also filter out all the dependencies on *.ver. We need
81  * to make sure that the generated version checksum are globally up
82  * to date before even starting the recursive build, so it's too late
83  * at this point anyway.
84  *
85  * We don't even try to really parse the header files, but
86  * merely grep, i.e. if CONFIG_FOO is mentioned in a comment, it will
87  * be picked up as well. It's not a problem with respect to
88  * correctness, since that can only give too many dependencies, thus
89  * we cannot miss a rebuild. Since people tend to not mention totally
90  * unrelated CONFIG_ options all over the place, it's not an
91  * efficiency problem either.
92  *
93  * (Note: it'd be easy to port over the complete mkdep state machine,
94  *  but I don't think the added complexity is worth it)
95  */
96 
97 #include <sys/types.h>
98 #include <sys/stat.h>
99 #include <unistd.h>
100 #include <fcntl.h>
101 #include <string.h>
102 #include <stdlib.h>
103 #include <stdio.h>
104 #include <ctype.h>
105 
106 static void usage(void)
107 {
108 	fprintf(stderr, "Usage: fixdep <depfile> <target> <cmdline>\n");
109 	exit(1);
110 }
111 
112 /*
113  * Print out a dependency path from a symbol name
114  */
115 static void print_dep(const char *m, int slen, const char *dir)
116 {
117 	int c, prev_c = '/', i;
118 
119 	printf("    $(wildcard %s/", dir);
120 	for (i = 0; i < slen; i++) {
121 		c = m[i];
122 		if (c == '_')
123 			c = '/';
124 		else
125 			c = tolower(c);
126 		if (c != '/' || prev_c != '/')
127 			putchar(c);
128 		prev_c = c;
129 	}
130 	printf(".h) \\\n");
131 }
132 
133 struct item {
134 	struct item	*next;
135 	unsigned int	len;
136 	unsigned int	hash;
137 	char		name[0];
138 };
139 
140 #define HASHSZ 256
141 static struct item *hashtab[HASHSZ];
142 
143 static unsigned int strhash(const char *str, unsigned int sz)
144 {
145 	/* fnv32 hash */
146 	unsigned int i, hash = 2166136261U;
147 
148 	for (i = 0; i < sz; i++)
149 		hash = (hash ^ str[i]) * 0x01000193;
150 	return hash;
151 }
152 
153 /*
154  * Lookup a value in the configuration string.
155  */
156 static int is_defined_config(const char *name, int len, unsigned int hash)
157 {
158 	struct item *aux;
159 
160 	for (aux = hashtab[hash % HASHSZ]; aux; aux = aux->next) {
161 		if (aux->hash == hash && aux->len == len &&
162 		    memcmp(aux->name, name, len) == 0)
163 			return 1;
164 	}
165 	return 0;
166 }
167 
168 /*
169  * Add a new value to the configuration string.
170  */
171 static void define_config(const char *name, int len, unsigned int hash)
172 {
173 	struct item *aux = malloc(sizeof(*aux) + len);
174 
175 	if (!aux) {
176 		perror("fixdep:malloc");
177 		exit(1);
178 	}
179 	memcpy(aux->name, name, len);
180 	aux->len = len;
181 	aux->hash = hash;
182 	aux->next = hashtab[hash % HASHSZ];
183 	hashtab[hash % HASHSZ] = aux;
184 }
185 
186 /*
187  * Record the use of a CONFIG_* word.
188  */
189 static void use_config(const char *m, int slen)
190 {
191 	unsigned int hash = strhash(m, slen);
192 
193 	if (is_defined_config(m, slen, hash))
194 	    return;
195 
196 	define_config(m, slen, hash);
197 	print_dep(m, slen, "include/config");
198 }
199 
200 /* test if s ends in sub */
201 static int str_ends_with(const char *s, int slen, const char *sub)
202 {
203 	int sublen = strlen(sub);
204 
205 	if (sublen > slen)
206 		return 0;
207 
208 	return !memcmp(s + slen - sublen, sub, sublen);
209 }
210 
211 static void parse_config_file(const char *p)
212 {
213 	const char *q, *r;
214 	const char *start = p;
215 
216 	while ((p = strstr(p, "CONFIG_"))) {
217 		if (p > start && (isalnum(p[-1]) || p[-1] == '_')) {
218 			p += 7;
219 			continue;
220 		}
221 		p += 7;
222 		q = p;
223 		while (*q && (isalnum(*q) || *q == '_'))
224 			q++;
225 		if (str_ends_with(p, q - p, "_MODULE"))
226 			r = q - 7;
227 		else
228 			r = q;
229 		if (r > p)
230 			use_config(p, r - p);
231 		p = q;
232 	}
233 }
234 
235 static void *read_file(const char *filename)
236 {
237 	struct stat st;
238 	int fd;
239 	char *buf;
240 
241 	fd = open(filename, O_RDONLY);
242 	if (fd < 0) {
243 		fprintf(stderr, "fixdep: error opening file: ");
244 		perror(filename);
245 		exit(2);
246 	}
247 	if (fstat(fd, &st) < 0) {
248 		fprintf(stderr, "fixdep: error fstat'ing file: ");
249 		perror(filename);
250 		exit(2);
251 	}
252 	buf = malloc(st.st_size + 1);
253 	if (!buf) {
254 		perror("fixdep: malloc");
255 		exit(2);
256 	}
257 	if (read(fd, buf, st.st_size) != st.st_size) {
258 		perror("fixdep: read");
259 		exit(2);
260 	}
261 	buf[st.st_size] = '\0';
262 	close(fd);
263 
264 	return buf;
265 }
266 
267 /* Ignore certain dependencies */
268 static int is_ignored_file(const char *s, int len)
269 {
270 	return str_ends_with(s, len, "include/generated/autoconf.h") ||
271 	       str_ends_with(s, len, "include/generated/autoksyms.h") ||
272 	       str_ends_with(s, len, ".ver");
273 }
274 
275 /*
276  * Important: The below generated source_foo.o and deps_foo.o variable
277  * assignments are parsed not only by make, but also by the rather simple
278  * parser in scripts/mod/sumversion.c.
279  */
280 static void parse_dep_file(char *m, const char *target)
281 {
282 	char *p;
283 	int is_last, is_target;
284 	int saw_any_target = 0;
285 	int is_first_dep = 0;
286 	void *buf;
287 
288 	while (1) {
289 		/* Skip any "white space" */
290 		while (*m == ' ' || *m == '\\' || *m == '\n')
291 			m++;
292 
293 		if (!*m)
294 			break;
295 
296 		/* Find next "white space" */
297 		p = m;
298 		while (*p && *p != ' ' && *p != '\\' && *p != '\n')
299 			p++;
300 		is_last = (*p == '\0');
301 		/* Is the token we found a target name? */
302 		is_target = (*(p-1) == ':');
303 		/* Don't write any target names into the dependency file */
304 		if (is_target) {
305 			/* The /next/ file is the first dependency */
306 			is_first_dep = 1;
307 		} else if (!is_ignored_file(m, p - m)) {
308 			*p = '\0';
309 
310 			/*
311 			 * Do not list the source file as dependency, so that
312 			 * kbuild is not confused if a .c file is rewritten
313 			 * into .S or vice versa. Storing it in source_* is
314 			 * needed for modpost to compute srcversions.
315 			 */
316 			if (is_first_dep) {
317 				/*
318 				 * If processing the concatenation of multiple
319 				 * dependency files, only process the first
320 				 * target name, which will be the original
321 				 * source name, and ignore any other target
322 				 * names, which will be intermediate temporary
323 				 * files.
324 				 */
325 				if (!saw_any_target) {
326 					saw_any_target = 1;
327 					printf("source_%s := %s\n\n",
328 					       target, m);
329 					printf("deps_%s := \\\n", target);
330 				}
331 				is_first_dep = 0;
332 			} else {
333 				printf("  %s \\\n", m);
334 			}
335 
336 			buf = read_file(m);
337 			parse_config_file(buf);
338 			free(buf);
339 		}
340 
341 		if (is_last)
342 			break;
343 
344 		/*
345 		 * Start searching for next token immediately after the first
346 		 * "whitespace" character that follows this token.
347 		 */
348 		m = p + 1;
349 	}
350 
351 	if (!saw_any_target) {
352 		fprintf(stderr, "fixdep: parse error; no targets found\n");
353 		exit(1);
354 	}
355 
356 	printf("\n%s: $(deps_%s)\n\n", target, target);
357 	printf("$(deps_%s):\n", target);
358 }
359 
360 int main(int argc, char *argv[])
361 {
362 	const char *depfile, *target, *cmdline;
363 	void *buf;
364 
365 	if (argc != 4)
366 		usage();
367 
368 	depfile = argv[1];
369 	target = argv[2];
370 	cmdline = argv[3];
371 
372 	printf("cmd_%s := %s\n\n", target, cmdline);
373 
374 	buf = read_file(depfile);
375 	parse_dep_file(buf, target);
376 	free(buf);
377 
378 	return 0;
379 }
380