/*1* "Optimize" a list of dependencies as spit out by gcc -MD2* for the kernel build3* ===========================================================================4*5* Author Kai Germaschewski6* Copyright 2002 by Kai Germaschewski <[email protected]>7*8* This software may be used and distributed according to the terms9* of the GNU General Public License, incorporated herein by reference.10*11*12* Introduction:13*14* gcc produces a very nice and correct list of dependencies which15* tells make when to remake a file.16*17* To use this list as-is however has the drawback that virtually18* every file in the kernel includes autoconf.h.19*20* If the user re-runs make *config, autoconf.h will be21* regenerated. make notices that and will rebuild every file which22* includes autoconf.h, i.e. basically all files. This is extremely23* annoying if the user just changed CONFIG_HIS_DRIVER from n to m.24*25* So we play the same trick that "mkdep" played before. We replace26* the dependency on autoconf.h by a dependency on every config27* option which is mentioned in any of the listed prerequisites.28*29* kconfig populates a tree in include/config/ with an empty file30* for each config symbol and when the configuration is updated31* the files representing changed config options are touched32* which then let make pick up the changes and the files that use33* the config symbols are rebuilt.34*35* So if the user changes his CONFIG_HIS_DRIVER option, only the objects36* which depend on "include/config/HIS_DRIVER" will be rebuilt,37* so most likely only his driver ;-)38*39* The idea above dates, by the way, back to Michael E Chastain, AFAIK.40*41* So to get dependencies right, there are two issues:42* o if any of the files the compiler read changed, we need to rebuild43* o if the command line given to the compile the file changed, we44* better rebuild as well.45*46* The former is handled by using the -MD output, the later by saving47* the command line used to compile the old object and comparing it48* to the one we would now use.49*50* Again, also this idea is pretty old and has been discussed on51* kbuild-devel a long time ago. I don't have a sensibly working52* internet connection right now, so I rather don't mention names53* without double checking.54*55* This code here has been based partially based on mkdep.c, which56* says the following about its history:57*58* Copyright abandoned, Michael Chastain, <mailto:[email protected]>.59* This is a C version of syncdep.pl by Werner Almesberger.60*61*62* It is invoked as63*64* fixdep <depfile> <target> <cmdline>65*66* and will read the dependency file <depfile>67*68* The transformed dependency snipped is written to stdout.69*70* It first generates a line71*72* savedcmd_<target> = <cmdline>73*74* and then basically copies the .<target>.d file to stdout, in the75* process filtering out the dependency on autoconf.h and adding76* dependencies on include/config/MY_OPTION for every77* CONFIG_MY_OPTION encountered in any of the prerequisites.78*79* We don't even try to really parse the header files, but80* merely grep, i.e. if CONFIG_FOO is mentioned in a comment, it will81* be picked up as well. It's not a problem with respect to82* correctness, since that can only give too many dependencies, thus83* we cannot miss a rebuild. Since people tend to not mention totally84* unrelated CONFIG_ options all over the place, it's not an85* efficiency problem either.86*87* (Note: it'd be easy to port over the complete mkdep state machine,88* but I don't think the added complexity is worth it)89*/9091#include <sys/types.h>92#include <sys/stat.h>93#include <unistd.h>94#include <fcntl.h>95#include <string.h>96#include <stdbool.h>97#include <stdlib.h>98#include <stdio.h>99#include <ctype.h>100101static void usage(void)102{103fprintf(stderr, "Usage: fixdep <depfile> <target> <cmdline>\n");104exit(1);105}106107struct item {108struct item *next;109unsigned int len;110unsigned int hash;111char name[];112};113114#define HASHSZ 256115static struct item *config_hashtab[HASHSZ], *file_hashtab[HASHSZ];116117static unsigned int strhash(const char *str, unsigned int sz)118{119/* fnv32 hash */120unsigned int i, hash = 2166136261U;121122for (i = 0; i < sz; i++)123hash = (hash ^ str[i]) * 0x01000193;124return hash;125}126127/*128* Add a new value to the configuration string.129*/130static void add_to_hashtable(const char *name, int len, unsigned int hash,131struct item *hashtab[])132{133struct item *aux = malloc(sizeof(*aux) + len);134135if (!aux) {136perror("fixdep:malloc");137exit(1);138}139memcpy(aux->name, name, len);140aux->len = len;141aux->hash = hash;142aux->next = hashtab[hash % HASHSZ];143hashtab[hash % HASHSZ] = aux;144}145146/*147* Lookup a string in the hash table. If found, just return true.148* If not, add it to the hashtable and return false.149*/150static bool in_hashtable(const char *name, int len, struct item *hashtab[])151{152struct item *aux;153unsigned int hash = strhash(name, len);154155for (aux = hashtab[hash % HASHSZ]; aux; aux = aux->next) {156if (aux->hash == hash && aux->len == len &&157memcmp(aux->name, name, len) == 0)158return true;159}160161add_to_hashtable(name, len, hash, hashtab);162163return false;164}165166/*167* Record the use of a CONFIG_* word.168*/169static void use_config(const char *m, int slen)170{171if (in_hashtable(m, slen, config_hashtab))172return;173174/* Print out a dependency path from a symbol name. */175printf(" $(wildcard include/config/%.*s) \\\n", slen, m);176}177178/* test if s ends in sub */179static int str_ends_with(const char *s, int slen, const char *sub)180{181int sublen = strlen(sub);182183if (sublen > slen)184return 0;185186return !memcmp(s + slen - sublen, sub, sublen);187}188189static void parse_config_file(const char *p)190{191const char *q, *r;192const char *start = p;193194while ((p = strstr(p, "CONFIG_"))) {195if (p > start && (isalnum(p[-1]) || p[-1] == '_')) {196p += 7;197continue;198}199p += 7;200q = p;201while (isalnum(*q) || *q == '_')202q++;203if (str_ends_with(p, q - p, "_MODULE"))204r = q - 7;205else206r = q;207if (r > p)208use_config(p, r - p);209p = q;210}211}212213static void *read_file(const char *filename)214{215struct stat st;216int fd;217char *buf;218219fd = open(filename, O_RDONLY);220if (fd < 0) {221fprintf(stderr, "fixdep: error opening file: ");222perror(filename);223exit(2);224}225if (fstat(fd, &st) < 0) {226fprintf(stderr, "fixdep: error fstat'ing file: ");227perror(filename);228exit(2);229}230buf = malloc(st.st_size + 1);231if (!buf) {232perror("fixdep: malloc");233exit(2);234}235if (read(fd, buf, st.st_size) != st.st_size) {236perror("fixdep: read");237exit(2);238}239buf[st.st_size] = '\0';240close(fd);241242return buf;243}244245/* Ignore certain dependencies */246static int is_ignored_file(const char *s, int len)247{248return str_ends_with(s, len, "include/generated/autoconf.h");249}250251/* Do not parse these files */252static int is_no_parse_file(const char *s, int len)253{254/* rustc may list binary files in dep-info */255return str_ends_with(s, len, ".rlib") ||256str_ends_with(s, len, ".rmeta") ||257str_ends_with(s, len, ".so");258}259260/*261* Important: The below generated source_foo.o and deps_foo.o variable262* assignments are parsed not only by make, but also by the rather simple263* parser in scripts/mod/sumversion.c.264*/265static void parse_dep_file(char *p, const char *target)266{267bool saw_any_target = false;268bool is_target = true;269bool is_source = false;270bool need_parse;271char *q, saved_c;272273while (*p) {274/* handle some special characters first. */275switch (*p) {276case '#':277/*278* skip comments.279* rustc may emit comments to dep-info.280*/281p++;282while (*p != '\0' && *p != '\n') {283/*284* escaped newlines continue the comment across285* multiple lines.286*/287if (*p == '\\')288p++;289p++;290}291continue;292case ' ':293case '\t':294/* skip whitespaces */295p++;296continue;297case '\\':298/*299* backslash/newline combinations continue the300* statement. Skip it just like a whitespace.301*/302if (*(p + 1) == '\n') {303p += 2;304continue;305}306break;307case '\n':308/*309* Makefiles use a line-based syntax, where the newline310* is the end of a statement. After seeing a newline,311* we expect the next token is a target.312*/313p++;314is_target = true;315continue;316case ':':317/*318* assume the first dependency after a colon as the319* source file.320*/321p++;322is_target = false;323is_source = true;324continue;325}326327/* find the end of the token */328q = p;329while (*q != ' ' && *q != '\t' && *q != '\n' && *q != '#' && *q != ':') {330if (*q == '\\') {331/*332* backslash/newline combinations work like as333* a whitespace, so this is the end of token.334*/335if (*(q + 1) == '\n')336break;337338/* escaped special characters */339if (*(q + 1) == '#' || *(q + 1) == ':') {340memmove(p + 1, p, q - p);341p++;342}343344q++;345}346347if (*q == '\0')348break;349q++;350}351352/* Just discard the target */353if (is_target) {354p = q;355continue;356}357358saved_c = *q;359*q = '\0';360need_parse = false;361362/*363* Do not list the source file as dependency, so that kbuild is364* not confused if a .c file is rewritten into .S or vice versa.365* Storing it in source_* is needed for modpost to compute366* srcversions.367*/368if (is_source) {369/*370* The DT build rule concatenates multiple dep files.371* When processing them, only process the first source372* name, which will be the original one, and ignore any373* other source names, which will be intermediate374* temporary files.375*376* rustc emits the same dependency list for each377* emission type. It is enough to list the source name378* just once.379*/380if (!saw_any_target) {381saw_any_target = true;382printf("source_%s := %s\n\n", target, p);383printf("deps_%s := \\\n", target);384need_parse = true;385}386} else if (!is_ignored_file(p, q - p) &&387!in_hashtable(p, q - p, file_hashtab)) {388printf(" %s \\\n", p);389need_parse = true;390}391392if (need_parse && !is_no_parse_file(p, q - p)) {393void *buf;394395buf = read_file(p);396parse_config_file(buf);397free(buf);398}399400is_source = false;401*q = saved_c;402p = q;403}404405if (!saw_any_target) {406fprintf(stderr, "fixdep: parse error; no targets found\n");407exit(1);408}409410printf("\n%s: $(deps_%s)\n\n", target, target);411printf("$(deps_%s):\n", target);412}413414int main(int argc, char *argv[])415{416const char *depfile, *target, *cmdline;417void *buf;418419if (argc != 4)420usage();421422depfile = argv[1];423target = argv[2];424cmdline = argv[3];425426printf("savedcmd_%s := %s\n\n", target, cmdline);427428buf = read_file(depfile);429parse_dep_file(buf, target);430free(buf);431432fflush(stdout);433434/*435* In the intended usage, the stdout is redirected to .*.cmd files.436* Call ferror() to catch errors such as "No space left on device".437*/438if (ferror(stdout)) {439fprintf(stderr, "fixdep: not all data was written to the output\n");440exit(1);441}442443return 0;444}445446447