/*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>100101#include <xalloc.h>102103static void usage(void)104{105fprintf(stderr, "Usage: fixdep <depfile> <target> <cmdline>\n");106exit(1);107}108109struct item {110struct item *next;111unsigned int len;112unsigned int hash;113char name[];114};115116#define HASHSZ 256117static struct item *config_hashtab[HASHSZ], *file_hashtab[HASHSZ];118119static unsigned int strhash(const char *str, unsigned int sz)120{121/* fnv32 hash */122unsigned int i, hash = 2166136261U;123124for (i = 0; i < sz; i++)125hash = (hash ^ str[i]) * 0x01000193;126return hash;127}128129/*130* Add a new value to the configuration string.131*/132static void add_to_hashtable(const char *name, int len, unsigned int hash,133struct item *hashtab[])134{135struct item *aux;136137aux = xmalloc(sizeof(*aux) + len);138memcpy(aux->name, name, len);139aux->len = len;140aux->hash = hash;141aux->next = hashtab[hash % HASHSZ];142hashtab[hash % HASHSZ] = aux;143}144145/*146* Lookup a string in the hash table. If found, just return true.147* If not, add it to the hashtable and return false.148*/149static bool in_hashtable(const char *name, int len, struct item *hashtab[])150{151struct item *aux;152unsigned int hash = strhash(name, len);153154for (aux = hashtab[hash % HASHSZ]; aux; aux = aux->next) {155if (aux->hash == hash && aux->len == len &&156memcmp(aux->name, name, len) == 0)157return true;158}159160add_to_hashtable(name, len, hash, hashtab);161162return false;163}164165/*166* Record the use of a CONFIG_* word.167*/168static void use_config(const char *m, int slen)169{170if (in_hashtable(m, slen, config_hashtab))171return;172173/* Print out a dependency path from a symbol name. */174printf(" $(wildcard include/config/%.*s) \\\n", slen, m);175}176177/* test if s ends in sub */178static int str_ends_with(const char *s, int slen, const char *sub)179{180int sublen = strlen(sub);181182if (sublen > slen)183return 0;184185return !memcmp(s + slen - sublen, sub, sublen);186}187188static void parse_config_file(const char *p)189{190const char *q, *r;191const char *start = p;192193while ((p = strstr(p, "CONFIG_"))) {194if (p > start && (isalnum(p[-1]) || p[-1] == '_')) {195p += 7;196continue;197}198p += 7;199q = p;200while (isalnum(*q) || *q == '_')201q++;202if (str_ends_with(p, q - p, "_MODULE"))203r = q - 7;204else205r = q;206if (r > p)207use_config(p, r - p);208p = q;209}210}211212static void *read_file(const char *filename)213{214struct stat st;215int fd;216char *buf;217218fd = open(filename, O_RDONLY);219if (fd < 0) {220fprintf(stderr, "fixdep: error opening file: ");221perror(filename);222exit(2);223}224if (fstat(fd, &st) < 0) {225fprintf(stderr, "fixdep: error fstat'ing file: ");226perror(filename);227exit(2);228}229buf = xmalloc(st.st_size + 1);230if (read(fd, buf, st.st_size) != st.st_size) {231perror("fixdep: read");232exit(2);233}234buf[st.st_size] = '\0';235close(fd);236237return buf;238}239240/* Ignore certain dependencies */241static int is_ignored_file(const char *s, int len)242{243return str_ends_with(s, len, "include/generated/autoconf.h");244}245246/* Do not parse these files */247static int is_no_parse_file(const char *s, int len)248{249/* rustc may list binary files in dep-info */250return str_ends_with(s, len, ".rlib") ||251str_ends_with(s, len, ".rmeta") ||252str_ends_with(s, len, ".so");253}254255/*256* Important: The below generated source_foo.o and deps_foo.o variable257* assignments are parsed not only by make, but also by the rather simple258* parser in scripts/mod/sumversion.c.259*/260static void parse_dep_file(char *p, const char *target)261{262bool saw_any_target = false;263bool is_target = true;264bool is_source = false;265bool need_parse;266char *q, saved_c;267268while (*p) {269/* handle some special characters first. */270switch (*p) {271case '#':272/*273* skip comments.274* rustc may emit comments to dep-info.275*/276p++;277while (*p != '\0' && *p != '\n') {278/*279* escaped newlines continue the comment across280* multiple lines.281*/282if (*p == '\\')283p++;284p++;285}286continue;287case ' ':288case '\t':289/* skip whitespaces */290p++;291continue;292case '\\':293/*294* backslash/newline combinations continue the295* statement. Skip it just like a whitespace.296*/297if (*(p + 1) == '\n') {298p += 2;299continue;300}301break;302case '\n':303/*304* Makefiles use a line-based syntax, where the newline305* is the end of a statement. After seeing a newline,306* we expect the next token is a target.307*/308p++;309is_target = true;310continue;311case ':':312/*313* assume the first dependency after a colon as the314* source file.315*/316p++;317is_target = false;318is_source = true;319continue;320}321322/* find the end of the token */323q = p;324while (*q != ' ' && *q != '\t' && *q != '\n' && *q != '#' && *q != ':') {325if (*q == '\\') {326/*327* backslash/newline combinations work like as328* a whitespace, so this is the end of token.329*/330if (*(q + 1) == '\n')331break;332333/* escaped special characters */334if (*(q + 1) == '#' || *(q + 1) == ':') {335memmove(p + 1, p, q - p);336p++;337}338339q++;340}341342if (*q == '\0')343break;344q++;345}346347/* Just discard the target */348if (is_target) {349p = q;350continue;351}352353saved_c = *q;354*q = '\0';355need_parse = false;356357/*358* Do not list the source file as dependency, so that kbuild is359* not confused if a .c file is rewritten into .S or vice versa.360* Storing it in source_* is needed for modpost to compute361* srcversions.362*/363if (is_source) {364/*365* The DT build rule concatenates multiple dep files.366* When processing them, only process the first source367* name, which will be the original one, and ignore any368* other source names, which will be intermediate369* temporary files.370*371* rustc emits the same dependency list for each372* emission type. It is enough to list the source name373* just once.374*/375if (!saw_any_target) {376saw_any_target = true;377printf("source_%s := %s\n\n", target, p);378printf("deps_%s := \\\n", target);379need_parse = true;380}381} else if (!is_ignored_file(p, q - p) &&382!in_hashtable(p, q - p, file_hashtab)) {383printf(" %s \\\n", p);384need_parse = true;385}386387if (need_parse && !is_no_parse_file(p, q - p)) {388void *buf;389390buf = read_file(p);391parse_config_file(buf);392free(buf);393}394395is_source = false;396*q = saved_c;397p = q;398}399400if (!saw_any_target) {401fprintf(stderr, "fixdep: parse error; no targets found\n");402exit(1);403}404405printf("\n%s: $(deps_%s)\n\n", target, target);406printf("$(deps_%s):\n", target);407}408409int main(int argc, char *argv[])410{411const char *depfile, *target, *cmdline;412void *buf;413414if (argc != 4)415usage();416417depfile = argv[1];418target = argv[2];419cmdline = argv[3];420421printf("savedcmd_%s := %s\n\n", target, cmdline);422423buf = read_file(depfile);424parse_dep_file(buf, target);425free(buf);426427fflush(stdout);428429/*430* In the intended usage, the stdout is redirected to .*.cmd files.431* Call ferror() to catch errors such as "No space left on device".432*/433if (ferror(stdout)) {434fprintf(stderr, "fixdep: not all data was written to the output\n");435exit(1);436}437438return 0;439}440441442