1 /* vi: set sw=4 ts=4: */
3 * Another fast dependencies generator for Makefiles, Version 4.2
5 * Copyright (C) 2005,2006 by Vladimir Oleynik <dzo@simtreas.ru>
7 * mmaping file may be originally by Linus Torvalds.
9 * infix parser/evaluator for #if expression
10 * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
11 * Copyright (c) 2001 Manuel Novoa III <mjn3@codepoet.org>
12 * Copyright (c) 2003 Vladimir Oleynik <dzo@simtreas.ru>
15 * Copyright (C) 2005 Manuel Novoa III <mjn3@codepoet.org>
17 * xmalloc() bb_xstrdup() bb_error_d():
18 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
21 * Copyright (C) 2003 Glenn McGrath
22 * Copyright (C) Vladimir Oleynik <dzo@simtreas.ru>
24 * (c) 2005,2006 Bernhard Fischer:
26 * - move "memory exhausted" into msg_enomem,
27 * - more verbose --help output.
30 * 1) find #define KEY VALUE or #undef KEY from include/bb_config.h
31 * 2) recursive find and scan *.[ch] files, but skips scan of include/config/
32 * 3) find #include "*.h" and KEYs using, if not as #define and #undef
33 * 4) generate dependencies to stdout
34 * pwd/file.o: include/config/key*.h found_include_*.h
35 * path/inc.h: include/config/key*.h found_included_include_*.h
36 * 5) save include/config/key*.h if changed after previous usage
37 * This program does not generate dependencies for #include <...>
38 * Config file can have #if #elif #else #ifdef #ifndef #endif lines
41 #define LOCAL_INCLUDE_PATH "include"
42 #define INCLUDE_CONFIG_PATH LOCAL_INCLUDE_PATH"/config"
43 #define INCLUDE_CONFIG_KEYS_PATH LOCAL_INCLUDE_PATH"/bb_config.h"
45 #define bb_mkdep_full_options \
47 "\n\t-I local_include_path include paths, default: \"" LOCAL_INCLUDE_PATH "\"" \
48 "\n\t-d don't generate depend" \
49 "\n\t-w show warning if include files not found" \
50 "\n\t-k include/config default: \"" INCLUDE_CONFIG_PATH "\"" \
51 "\n\t-c include/config.h configs, default: \"" INCLUDE_CONFIG_KEYS_PATH "\"" \
52 "\n\tdirs_to_scan default \".\""
54 #define bb_mkdep_terse_options "Usage: [-I local_include_paths] [-dw] " \
55 "[-k path_for_stored_keys] [dirs]"
59 #include <sys/types.h>
74 #define ATTRIBUTE __attribute__
76 #define ATTRIBUTE(a) /* nothing */
79 #if !(defined __USE_ISOC99 || (defined __GLIBC_HAVE_LONG_LONG && defined __USE_MISC))
80 #define strtoll strtol
83 /* partial and simplified libbb routine */
84 static void bb_error_d(const char *s, ...) ATTRIBUTE ((noreturn, format (printf, 1, 2)));
85 static char * bb_asprint(const char *format, ...) ATTRIBUTE ((format (printf, 1, 2)));
86 static char *bb_simplify_path(const char *path);
88 /* stolen from libbb as is */
89 typedef struct llist_s {
94 static const char msg_enomem[] = "memory exhausted";
96 /* inline realization for fast works */
97 static inline void *xmalloc(size_t size)
99 void *p = malloc(size);
102 bb_error_d(msg_enomem);
106 static inline char *bb_xstrdup(const char *s)
111 bb_error_d(msg_enomem);
116 static int dontgenerate_dep; /* flag -d usaged */
117 static int noiwarning; /* flag -w usaged */
118 static llist_t *configs; /* list of -c usaged and them stat() after parsed */
119 static llist_t *Iop; /* list of -I include usaged */
121 static char *pwd; /* current work directory */
122 static size_t replace; /* replace current work directory with build dir */
124 static const char *kp; /* KEY path, argument of -k used */
125 static size_t kp_len;
126 static struct stat st_kp; /* stat(kp) */
128 typedef struct BB_KEYS {
134 const char *src_have_this_key;
135 struct BB_KEYS *next;
138 static bb_key_t *key_top; /* list of found KEYs */
139 static bb_key_t *Ifound; /* list of parsed includes */
142 static void parse_conf_opt(const char *opt, const char *val, size_t key_sz);
143 static void parse_inc(const char *include, const char *fname);
145 static inline bb_key_t *check_key(bb_key_t *k, const char *nk, size_t key_sz)
149 for(cur = k; cur; cur = cur->next) {
150 if(key_sz == cur->key_sz && memcmp(cur->keyname, nk, key_sz) == 0) {
151 cur->checked = cur->stored_path;
158 static inline const char *lookup_key(const char *nk, size_t key_sz)
162 for(cur = key_top; cur; cur = cur->next) {
163 if(key_sz == cur->key_sz && memcmp(cur->keyname, nk, key_sz) == 0) {
170 /* for lexical analyser */
171 static int pagesizem1; /* padding mask = getpagesize() - 1 */
173 /* for speed tricks */
174 static char first_chars[1+UCHAR_MAX]; /* + L_EOF */
175 static char isalnums[1+UCHAR_MAX]; /* + L_EOF */
177 /* trick for fast find "define", "include", "undef",
178 "if((n)def)" "else", "endif" */
179 static const char * const preproc[] = {
180 /* 0 1 2 3 4 5 6 7 8 9 */
181 "", "efine", "lif", "lse", "ndif", "f", "fdef", "fndef", "nclude", "ndef" };
182 static const unsigned char first_chars_deiu[UCHAR_MAX] = {
183 [(int)'d'] = (unsigned char)(1|0x10), /* define */
184 [(int)'e'] = (unsigned char)(2|0x40), /* elif, else, endif */
185 [(int)'i'] = (unsigned char)(5|0x80), /* if ifdef ifndef include */
186 [(int)'u'] = (unsigned char)(9|0x90), /* undef */
189 #define CONFIG_MODE 0
190 #define IF0_MODE 1 /* #if 0 */
191 #define IF1_MODE 2 /* #if 1 */
192 #define ELSE0_MODE 4 /* #else found after #if 0 */
193 #define ELSE1_MODE 8 /* #else found after #if 1 */
194 #define ELIF1_MODE 16 /* #elif found after #if 1 */
195 #define FALSE_MODES (IF0_MODE|ELSE1_MODE|ELIF1_MODE)
197 #define yy_error_d(s) bb_error_d("%s:%d hmm, %s", fname, line, s)
200 #define S 0 /* start state */
201 #define STR '"' /* string */
202 #define CHR '\'' /* char */
203 #define REM '/' /* block comment */
204 #define BS '\\' /* back slash */
205 #define POUND '#' /* # */
206 #define D '1' /* #define preprocessor's directive */
207 #define EI '2' /* #elif preprocessor's directive */
208 #define E '3' /* #else preprocessor's directive */
209 #define EF '4' /* #endif preprocessor's directive */
210 #define F '5' /* #if preprocessor's directive */
211 #define IFD '6' /* #ifdef preprocessor's directive */
212 #define IFND '7' /* #ifndef preprocessor's directive */
213 #define I '8' /* #include preprocessor's directive */
214 #define U '9' /* #undef preprocessor's directive */
215 #define DK 'K' /* #define KEY... (config mode) */
216 #define ANY '*' /* any unparsed chars */
219 #define ID(c) ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_')
221 #define ISALNUM(c) (ID(c) || (c >= '0' && c <= '9'))
223 #define L_EOF (1+UCHAR_MAX)
225 #define getc0() do { c = (optr >= oend) ? L_EOF : *optr++; } while(0)
227 #define getc1() do { getc0(); if(c == BS) { getc0(); \
228 if(c == '\n') { line++; continue; } \
229 else { optr--; c = BS; } \
232 static char id_s[4096];
233 #define put_id(ic) do { if(id_len == sizeof(id_s)) goto too_long; \
234 id[id_len++] = ic; } while(0)
236 static char ifcpp_stack[1024];
237 static int ptr_ifcpp_stack;
238 #define push_mode() do { \
239 if(ptr_ifcpp_stack == (int)sizeof(ifcpp_stack)) \
240 yy_error_d("#if* stack overflow"); \
241 ifcpp_stack[ptr_ifcpp_stack++] = (char)mode; \
244 #define pop_mode() do { \
245 if(ptr_ifcpp_stack == 0) \
246 yy_error_d("unexpected #endif"); \
247 mode = ifcpp_stack[--ptr_ifcpp_stack]; \
251 typedef long long arith_t;
253 static arith_t arith (const char *expr, int *perrcode);
255 /* The code uses a simple two-stack algorithm. See
256 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
257 * for a detailed explanation of the infix-to-postfix algorithm on which
258 * this is based (this code differs in that it applies operators immediately
259 * to the stack instead of adding them to a queue to end up with an
262 #define arith_isspace(arithval) \
263 (arithval == ' ' || arithval == '\v' || arithval == '\t' || arithval == '\f')
266 typedef unsigned char operator;
268 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
269 * precedence, and 3 high bits are an ID unique across operators of that
270 * precedence. The ID portion is so that multiple operators can have the
271 * same precedence, ensuring that the leftmost one is evaluated first.
272 * Consider * and /. */
274 #define tok_decl(prec,id) (((id)<<5)|(prec))
275 #define PREC(op) ((op) & 0x1F)
277 #define TOK_LPAREN tok_decl(0,0)
279 #define TOK_COMMA tok_decl(1,0)
281 /* conditional is right associativity too */
282 #define TOK_CONDITIONAL tok_decl(2,0)
283 #define TOK_CONDITIONAL_SEP tok_decl(2,1)
285 #define TOK_OR tok_decl(3,0)
287 #define TOK_AND tok_decl(4,0)
289 #define TOK_BOR tok_decl(5,0)
291 #define TOK_BXOR tok_decl(6,0)
293 #define TOK_BAND tok_decl(7,0)
295 #define TOK_EQ tok_decl(8,0)
296 #define TOK_NE tok_decl(8,1)
298 #define TOK_LT tok_decl(9,0)
299 #define TOK_GT tok_decl(9,1)
300 #define TOK_GE tok_decl(9,2)
301 #define TOK_LE tok_decl(9,3)
303 #define TOK_LSHIFT tok_decl(10,0)
304 #define TOK_RSHIFT tok_decl(10,1)
306 #define TOK_ADD tok_decl(11,0)
307 #define TOK_SUB tok_decl(11,1)
309 #define TOK_MUL tok_decl(12,0)
310 #define TOK_DIV tok_decl(12,1)
311 #define TOK_REM tok_decl(12,2)
313 /* For now unary operators. */
315 #define TOK_BNOT tok_decl(UNARYPREC,0)
316 #define TOK_NOT tok_decl(UNARYPREC,1)
318 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
319 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
321 #define SPEC_PREC (UNARYPREC+2)
323 #define TOK_NUM tok_decl(SPEC_PREC, 0)
324 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
326 #define NUMPTR (*numstackptr)
328 typedef struct ARITCH_VAR_NUM {
330 arith_t contidional_second_val;
331 char contidional_second_val_initialized;
335 typedef struct CHK_VAR_RECURSIVE_LOOPED {
338 struct CHK_VAR_RECURSIVE_LOOPED *next;
339 } chk_var_recursive_looped_t;
341 static chk_var_recursive_looped_t *prev_chk_var_recursive;
344 static int arith_lookup_val(const char *var, size_t key_sz, arith_t *pval)
346 const char * p = lookup_key(var, key_sz);
351 /* recursive try as expression */
352 chk_var_recursive_looped_t *cur;
353 chk_var_recursive_looped_t cur_save;
355 for(cur = prev_chk_var_recursive; cur; cur = cur->next) {
356 if(cur->var_sz == key_sz && memcmp(cur->var, var, key_sz) == 0) {
357 /* expression recursion loop detected */
361 /* save current lookuped var name */
362 cur = prev_chk_var_recursive;
364 cur_save.var_sz = key_sz;
366 prev_chk_var_recursive = &cur_save;
368 *pval = arith (p, &errcode);
369 /* restore previous ptr after recursiving */
370 prev_chk_var_recursive = cur;
373 /* disallow undefined var */
374 fprintf(stderr, "%.*s ", (int)key_sz, var);
379 /* "applying" a token means performing it on the top elements on the integer
380 * stack. For a unary operator it will only change the top element, but a
381 * binary operator will pop two arguments and push a result */
383 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
386 arith_t numptr_val, rez;
388 if (NUMPTR == numstack) goto err; /* There is no operator that can work
390 numptr_m1 = NUMPTR - 1;
392 rez = numptr_m1->val;
393 if (op == TOK_UMINUS)
395 else if (op == TOK_NOT)
397 else if (op == TOK_BNOT)
399 else if (op != TOK_UPLUS) {
400 /* Binary operators */
402 /* check and binary operators need two arguments */
403 if (numptr_m1 == numstack) goto err;
405 /* ... and they pop one */
408 if (op == TOK_CONDITIONAL) {
409 if(! numptr_m1->contidional_second_val_initialized) {
410 /* protect $((expr1 ? expr2)) without ": expr" */
413 rez = numptr_m1->contidional_second_val;
414 } else if(numptr_m1->contidional_second_val_initialized) {
415 /* protect $((expr1 : expr2)) without "expr ? " */
418 numptr_m1 = NUMPTR - 1;
419 if (op == TOK_CONDITIONAL) {
420 numptr_m1->contidional_second_val = rez;
422 rez = numptr_m1->val;
425 else if (op == TOK_OR)
426 rez = numptr_val || rez;
427 else if (op == TOK_BAND)
429 else if (op == TOK_BXOR)
431 else if (op == TOK_AND)
432 rez = rez && numptr_val;
433 else if (op == TOK_EQ)
434 rez = (rez == numptr_val);
435 else if (op == TOK_NE)
436 rez = (rez != numptr_val);
437 else if (op == TOK_GE)
438 rez = (rez >= numptr_val);
439 else if (op == TOK_RSHIFT)
441 else if (op == TOK_LSHIFT)
443 else if (op == TOK_GT)
444 rez = (rez > numptr_val);
445 else if (op == TOK_LT)
446 rez = (rez < numptr_val);
447 else if (op == TOK_LE)
448 rez = (rez <= numptr_val);
449 else if (op == TOK_MUL)
451 else if (op == TOK_ADD)
453 else if (op == TOK_SUB)
455 else if (op == TOK_COMMA)
457 else if (op == TOK_CONDITIONAL_SEP) {
458 if (numptr_m1 == numstack) {
459 /* protect $((expr : expr)) without "expr ? " */
462 numptr_m1->contidional_second_val_initialized = op;
463 numptr_m1->contidional_second_val = numptr_val;
465 else if (op == TOK_CONDITIONAL) {
467 numptr_val : numptr_m1->contidional_second_val;
469 else if(numptr_val==0) /* zero divisor check */
471 else if (op == TOK_DIV)
473 else if (op == TOK_REM)
476 numptr_m1->val = rez;
481 /* longest must first */
482 static const char op_tokens[] = {
483 '<','<', 0, TOK_LSHIFT,
484 '>','>', 0, TOK_RSHIFT,
504 '?', 0, TOK_CONDITIONAL,
505 ':', 0, TOK_CONDITIONAL_SEP,
511 #define endexpression &op_tokens[sizeof(op_tokens)-7]
514 * Return of a legal variable name (a letter or underscore followed by zero or
515 * more letters, underscores, and digits).
519 endofname(const char *name)
534 static arith_t arith (const char *expr, int *perrcode)
536 char arithval; /* Current character under analysis */
537 operator lasttok, op;
540 const char *p = endexpression;
543 size_t datasizes = strlen(expr) + 2;
545 /* Stack of integers */
546 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
547 * in any given correct or incorrect expression is left as an exercise to
549 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
550 *numstackptr = numstack;
551 /* Stack of operator tokens */
552 operator *stack = alloca((datasizes) * sizeof(operator)),
555 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
556 *perrcode = errcode = 0;
559 if ((arithval = *expr) == 0) {
560 if (p == endexpression) {
561 /* Null expression. */
563 return (*perrcode = -1);
566 /* This is only reached after all tokens have been extracted from the
567 * input stream. If there are still tokens on the operator stack, they
568 * are to be applied in order. At the end, there should be a final
569 * result on the integer stack */
571 if (expr != endexpression + 1) {
572 /* If we haven't done so already, */
573 /* append a closing right paren */
574 expr = endexpression;
575 /* and let the loop process it. */
578 /* At this point, we're done with the expression. */
579 if (numstackptr != numstack+1) {
580 /* ... but if there isn't, it's bad */
585 return numstack->val;
587 /* Continue processing the expression. */
588 if (arith_isspace(arithval)) {
589 /* Skip whitespace */
592 if((p = endofname(expr)) != expr) {
593 size_t var_name_size = (p-expr);
595 if(var_name_size == 7 &&
596 strncmp(expr, "defined", var_name_size) == 0) {
600 while(arith_isspace(*p)) p++;
603 while(arith_isspace(*p)) p++;
607 if((p = endofname(expr)) == expr)
609 var_name_size = (p-expr);
610 while(arith_isspace(*p)) p++;
611 if(brace_form && *p++ != ')')
613 v = lookup_key(expr, var_name_size);
614 numstackptr->val = (v != NULL) ? 1 : 0;
616 errcode = arith_lookup_val(expr, var_name_size,
617 &(numstackptr->val));
618 if(errcode) goto ret;
622 numstackptr->contidional_second_val_initialized = 0;
626 } else if (arithval >= '0' && arithval <= '9') {
627 numstackptr->val = strtoll(expr, (char **) &expr, 0);
628 while(*expr == 'l' || *expr == 'L' || *expr == 'u' ||
633 for(p = op_tokens; ; p++) {
637 /* strange operator not found */
640 for(o = expr; *p && *o == *p; p++)
647 /* skip tail uncompared token */
650 /* skip zero delim */
655 /* Plus and minus are binary (not unary) _only_ if the last
656 * token was as number, or a right paren (which pretends to be
657 * a number, since it evaluates to one). Think about it.
659 if (lasttok != TOK_NUM) {
662 else if(op == TOK_SUB)
665 /* We don't want a unary operator to cause recursive descent on the
666 * stack, because there can be many in a row and it could cause an
667 * operator to be evaluated before its argument is pushed onto the
669 /* But for binary operators, "apply" everything on the operator
670 * stack until we find an operator with a lesser priority than the
671 * one we have just extracted. */
672 /* Left paren is given the lowest priority so it will never be
673 * "applied" in this way.
674 * if associativity is right and priority eq, applied also skip
677 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
678 /* not left paren or unary */
679 if (lasttok != TOK_NUM) {
680 /* binary op must be preceded by a num */
683 while (stackptr != stack) {
684 if (op == TOK_RPAREN) {
685 /* The algorithm employed here is simple: while we don't
686 * hit an open paren nor the bottom of the stack, pop
687 * tokens and apply them */
688 if (stackptr[-1] == TOK_LPAREN) {
690 /* Any operator directly after a */
692 /* close paren should consider itself binary */
696 operator prev_prec = PREC(stackptr[-1]);
698 if (prev_prec < prec)
700 /* check right assoc */
701 if(prev_prec == prec && prec == PREC(TOK_CONDITIONAL))
704 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
705 if(errcode) goto ret;
707 if (op == TOK_RPAREN) {
712 /* Push this operator to the stack and remember it. */
713 *stackptr++ = lasttok = op;
721 /* stupid C lexical analyser for configs.h */
722 static void c_lex_config(const char *fname, long fsize)
728 size_t id_len = 0; /* stupid initialization */
729 unsigned char *optr, *oend;
730 int mode = CONFIG_MODE;
737 fprintf(stderr, "Warning: %s is empty\n", fname);
740 fd = open(fname, O_RDONLY);
745 mapsize = (fsize+pagesizem1) & ~pagesizem1;
746 map = mmap(NULL, mapsize, PROT_READ, MAP_PRIVATE, fd, 0);
747 if ((long) map == -1)
748 bb_error_d("%s: mmap: %m", fname);
750 optr = (unsigned char *)map;
759 /* [ \t]+ eat first space */
760 while(c == ' ' || c == '\t')
764 while(first_chars[c] == ANY) {
772 munmap(map, mapsize);
774 if(mode != CONFIG_MODE)
775 yy_error_d("expected #endif");
783 do getc0(); while(c != '\n' && c != L_EOF);
784 } else if(c == '*') {
785 /* <S>[/][*] goto parse block comments */
788 } else if(c == POUND) {
792 } else if(c == STR || c == CHR) {
800 /* <STR>\" or <CHR>\' */
804 /* <STR,CHR>\\ but is not <STR,CHR>\\\n */
807 if(c == '\n' || c == L_EOF)
808 yy_error_d("unterminated");
812 /* <S>[A-Z_a-z0-9] */
814 /* trick for fast drop id
815 if key with this first char undefined */
816 if(first_chars[c] == 0 || (mode & FALSE_MODES) != 0) {
817 /* skip <S>[A-Z_a-z0-9]+ */
818 do getc1(); while(isalnums[c]);
822 /* <S>[A-Z_a-z0-9]+ */
825 } while(isalnums[c]);
826 check_key(key_top, id, id_len);
831 /* begin preprocessor states */
833 yy_error_d("unexpected EOF");
838 yy_error_d("detected // in preprocessor line");
840 /* <#.*>[/][*] goto parse block comments */
844 yy_error_d("strange preprocessor line");
848 int diu = (int)first_chars_deiu[c]; /* preproc ptr */
852 int p_num_str, p_num_max;
861 p_num_str = diu & 0xf;
862 p_num_max = diu >> 4;
863 for(diu = p_num_str; diu <= p_num_max; diu++)
864 if(!strcmp(id, preproc[diu])) {
871 while(isalnums[c]) getc1();
873 } else if(state == EF) {
877 } else if(state == I) {
878 if(c == STR && (mode & FALSE_MODES) == 0) {
885 yy_error_d("unexpected EOF");
889 /* store "include.h" */
890 parse_inc(id, fname);
893 /* else another (may be wrong) #include ... */
895 } else if(state == F) {
899 while(c != '\n' && c != L_EOF) {
904 t = arith(id, &errcode);
907 yy_error_d("divide by zero");
908 else if (errcode == -4)
909 yy_error_d("undefined");
910 else if (errcode == -5)
911 yy_error_d("expression recursion loop detected");
913 yy_error_d("syntax error");
916 mode = t != 0 ? IF1_MODE : IF0_MODE;
918 } else if(state == IFD || state == IFND) {
919 /* save KEY from #if(n)def KEY ... */
928 yy_error_d("expected identifier");
929 v = lookup_key(id, id_len);
931 if(state == IFD && v == NULL)
933 else if(state == IFND && v != NULL)
936 } else if(state == EI) {
938 if(mode == CONFIG_MODE || mode == ELSE0_MODE || mode == ELSE1_MODE)
939 yy_error_d("unexpected #elif");
940 if(mode == IF0_MODE) {
947 } else if(state == E) {
948 if(mode == CONFIG_MODE || mode == ELSE0_MODE || mode == ELSE1_MODE)
949 yy_error_d("unexpected #else");
952 else if(mode == IF1_MODE)
955 } else if(state == D || state == U) {
956 /* save KEY from #"define"|"undef" ... */
962 yy_error_d("expected identifier");
964 if((mode & FALSE_MODES) == 0)
965 parse_conf_opt(id, NULL, id_len);
972 /* state==<DK> #define KEY[ ] */
973 size_t opt_len = id_len;
974 char *val = id + opt_len;
978 if(c == L_EOF || c == '\n')
985 /* trim tail spaces */
986 while(--sp >= val && (*sp == ' ' || *sp == '\t'
987 || *sp == '\f' || *sp == '\v'))
989 if((mode & FALSE_MODES) == 0)
990 parse_conf_opt(id, val, opt_len);
1003 yy_error_d("unexpected newline");
1005 } else if(c == L_EOF)
1006 yy_error_d("unexpected EOF");
1018 yy_error_d("phrase too long");
1021 /* trick for fast find "define", "include", "undef" */
1022 static const char first_chars_diu[UCHAR_MAX] = {
1023 [(int)'d'] = (char)5, /* strlen("define") - 1; */
1024 [(int)'i'] = (char)6, /* strlen("include") - 1; */
1025 [(int)'u'] = (char)4, /* strlen("undef") - 1; */
1031 #define D '5' /* #define preprocessor's directive */
1032 #define I '6' /* #include preprocessor's directive */
1033 #define U '4' /* #undef preprocessor's directive */
1035 /* stupid C lexical analyser for sources */
1036 static void c_lex_src(const char *fname, long fsize)
1042 size_t id_len = 0; /* stupid initialization */
1043 unsigned char *optr, *oend;
1050 fprintf(stderr, "Warning: %s is empty\n", fname);
1053 fd = open(fname, O_RDONLY);
1058 mapsize = (fsize+pagesizem1) & ~pagesizem1;
1059 map = mmap(NULL, mapsize, PROT_READ, MAP_PRIVATE, fd, 0);
1060 if ((long) map == -1)
1061 bb_error_d("%s: mmap: %m", fname);
1063 optr = (unsigned char *)map;
1064 oend = optr + fsize;
1072 /* [ \t]+ eat first space */
1073 while(c == ' ' || c == '\t')
1077 while(first_chars[c] == ANY) {
1085 munmap(map, mapsize);
1094 do getc0(); while(c != '\n' && c != L_EOF);
1095 } else if(c == '*') {
1096 /* <S>[/][*] goto parse block comments */
1099 } else if(c == POUND) {
1103 } else if(c == STR || c == CHR) {
1111 /* <STR>\" or <CHR>\' */
1115 /* <STR,CHR>\\ but is not <STR,CHR>\\\n */
1118 if(c == '\n' || c == L_EOF)
1119 yy_error_d("unterminated");
1123 /* <S>[A-Z_a-z0-9] */
1125 /* trick for fast drop id
1126 if key with this first char undefined */
1127 if(first_chars[c] == 0) {
1128 /* skip <S>[A-Z_a-z0-9]+ */
1129 do getc1(); while(isalnums[c]);
1133 /* <S>[A-Z_a-z0-9]+ */
1136 } while(isalnums[c]);
1137 check_key(key_top, id, id_len);
1142 /* begin preprocessor states */
1144 yy_error_d("unexpected EOF");
1149 yy_error_d("detected // in preprocessor line");
1151 /* <#.*>[/][*] goto parse block comments */
1155 yy_error_d("strange preprocessor line");
1157 if(state == POUND) {
1159 static const char * const p_preproc[] = {
1161 "", "", "", "", "ndef", "efine", "nclude"
1163 size_t diu = first_chars_diu[c]; /* strlen and p_preproc ptr */
1169 while(isalnums[c]) {
1173 /* str begins with c, read == strlen key and compared */
1174 if(diu == id_len && !memcmp(id, p_preproc[diu], diu)) {
1176 id_len = 0; /* common for save */
1179 while(isalnums[c]) getc1();
1181 } else if(state == I) {
1189 yy_error_d("unexpected EOF");
1193 /* store "include.h" */
1194 parse_inc(id, fname);
1197 /* else another (may be wrong) #include ... */
1199 } else /* if(state == D || state == U) */ {
1200 /* ignore depend with #define or #undef KEY */
1201 while(isalnums[c]) getc1();
1214 yy_error_d("unexpected newline");
1216 } else if(c == L_EOF)
1217 yy_error_d("unexpected EOF");
1229 yy_error_d("phrase too long");
1233 /* bb_simplify_path special variant for absolute pathname */
1234 static size_t bb_qa_simplify_path(char *path)
1242 if (*s == '/') { /* skip duplicate (or initial) slash */
1244 } else if (*s == '.') {
1245 if (s[1] == '/' || s[1] == 0) { /* remove extra '.' */
1247 } else if ((s[1] == '.') && (s[2] == '/' || s[2] == 0)) {
1250 while (*--p != '/'); /* omit previous dir */
1259 if ((p == path) || (*p != '/')) { /* not a trailing slash */
1260 ++p; /* so keep last character */
1267 static void parse_inc(const char *include, const char *fname)
1276 if(*include == '/') {
1278 ap = bb_xstrdup(include);
1284 p = strrchr(fname, '/'); /* fname has absolute pathname */
1286 /* find from current directory of source file */
1287 ap = bb_asprint("%.*s/%s", w, fname, include);
1291 key_sz = bb_qa_simplify_path(ap);
1292 cur = check_key(Ifound, ap, key_sz);
1294 cur->checked = cur->value;
1298 if(stat(ap, &st) == 0) {
1302 for(cfl = configs; cfl; cfl = cfl->link) {
1303 struct stat *config = (struct stat *)cfl->data;
1305 if (st.st_dev == config->st_dev && st.st_ino == config->st_ino) {
1306 /* skip depend with bb_configs.h */
1312 } else if(lo == NULL) {
1317 /* find from "-I include" specified directories */
1319 /* lo->data has absolute pathname */
1320 ap = bb_asprint("%s/%s", lo->data, include);
1324 cur = xmalloc(sizeof(bb_key_t));
1326 cur->key_sz = key_sz;
1327 cur->stored_path = ap;
1328 cur->value = cur->checked = p_i;
1329 if(p_i == NULL && noiwarning)
1330 fprintf(stderr, "%s: Warning: #include \"%s\" not found\n", fname, include);
1335 static size_t max_rec_sz;
1337 static void parse_conf_opt(const char *opt, const char *val, size_t key_sz)
1344 cur = check_key(key_top, opt, key_sz);
1346 /* already present */
1347 cur->checked = NULL; /* store only */
1348 if(cur->value == NULL && val == NULL)
1350 if(cur->value != NULL && val != NULL && !strcmp(cur->value, val))
1353 fprintf(stderr, "Warning: redefined %s\n", k);
1358 val_sz = strlen(val) + 1;
1359 recordsz = key_sz + val_sz + 1;
1360 if(max_rec_sz < recordsz)
1361 max_rec_sz = recordsz;
1362 cur = xmalloc(sizeof(bb_key_t) + recordsz);
1363 k = cur->keyname = memcpy(cur + 1, opt, key_sz);
1364 cur->keyname[key_sz] = '\0';
1365 cur->key_sz = key_sz;
1366 cur->checked = NULL;
1367 cur->src_have_this_key = NULL;
1368 cur->next = key_top;
1376 cur->value = p = cur->keyname + key_sz + 1;
1377 memcpy(p, val, val_sz);
1382 /* trick, save first char KEY for do fast identify id */
1383 first_chars[(int)*k] = *k;
1385 cur->stored_path = k = bb_asprint("%s/%s.h", kp, k);
1386 /* key conversion [A-Z_] -> [a-z/] */
1387 for(p = k + kp_len + 1; *p; p++) {
1388 if(*p >= 'A' && *p <= 'Z')
1389 *p = *p - 'A' + 'a';
1390 else if(*p == '_' && p[1] > '9') /* do not change A_1 to A/1 */
1395 static void store_keys(void)
1402 size_t recordsz = max_rec_sz * 2 + 10 * 2 + 16;
1403 /* buffer for double "#define KEY VAL\n" */
1404 char *record_buf = xmalloc(recordsz);
1406 for(cur = key_top; cur; cur = cur->next) {
1407 if(cur->src_have_this_key) {
1408 /* do generate record */
1410 if(cur->value == NULL) {
1411 recordsz = sprintf(record_buf, "#undef %s\n", k);
1413 const char *val = cur->value;
1415 recordsz = sprintf(record_buf, "#define %s\n", k);
1418 recordsz = sprintf(record_buf, "#define %s %s\n", k, val);
1420 recordsz = sprintf(record_buf, "#define %s%s\n", k, val);
1423 /* size_t -> ssize_t :( */
1424 rw_ret = (ssize_t)recordsz;
1425 /* check kp/key.h, compare after previous use */
1427 k = cur->stored_path;
1430 for(p = k + kp_len + 1; *p; p++) {
1431 /* Auto-create directories. */
1434 if (access(k, F_OK) != 0 && mkdir(k, 0755) != 0)
1435 bb_error_d("mkdir(%s): %m", k);
1441 if(st.st_size == (off_t)recordsz) {
1444 size_t padded = recordsz;
1446 /* 16-byte padding for read(2) and memcmp(3) */
1447 padded = (padded+15) & ~15;
1448 r_cmp = record_buf + padded;
1449 fd = open(k, O_RDONLY);
1450 if(fd < 0 || read(fd, r_cmp, recordsz) < rw_ret)
1451 bb_error_d("%s: %m", k);
1453 cmp_ok = memcmp(record_buf, r_cmp, recordsz) == 0;
1457 int fd = open(k, O_WRONLY|O_CREAT|O_TRUNC, 0644);
1458 if(fd < 0 || write(fd, record_buf, recordsz) < rw_ret)
1459 bb_error_d("%s: %m", k);
1466 static int show_dep(int first, bb_key_t *k, const char *name, const char *f)
1470 for(cur = k; cur; cur = cur->next) {
1475 printf("\n%s:", name);
1477 printf("\n%s/%s:", pwd, name);
1482 printf(" %s", cur->checked);
1484 cur->src_have_this_key = cur->checked;
1485 cur->checked = NULL;
1492 parse_chd(const char *fe, const char *p, size_t dirlen)
1497 static char dir_and_entry[4096];
1498 size_t fe_sz = strlen(fe) + 1;
1500 df_sz = dirlen + fe_sz + 1; /* dir/file\0 */
1501 if(df_sz > sizeof(dir_and_entry))
1502 bb_error_d("%s: file name too long", fe);
1504 /* sprintf(fp, "%s/%s", p, fe); */
1505 memcpy(fp, p, dirlen);
1507 memcpy(fp + dirlen + 1, fe, fe_sz);
1510 fprintf(stderr, "Warning: stat(%s): %m\n", fp);
1513 if(S_ISREG(st.st_mode)) {
1515 char *e = fp + df_sz - 3;
1517 if(*e++ != '.' || (*e != 'c' && *e != 'h')) {
1518 /* direntry is regular file, but is not *.[ch] */
1521 for(cfl = configs; cfl; cfl = cfl->link) {
1522 struct stat *config = (struct stat *)cfl->data;
1524 if (st.st_dev == config->st_dev && st.st_ino == config->st_ino) {
1525 /* skip already parsed bb_configs.h */
1529 /* direntry is *.[ch] regular file and is not configs */
1530 c_lex_src(fp, st.st_size);
1531 if(!dontgenerate_dep) {
1536 /* /src_dir/path/file.o to path/file.o */
1543 first = show_dep(1, Ifound, fp, e);
1544 first = show_dep(first, key_top, fp, e);
1548 show_dep(-1, key_top, NULL, NULL);
1551 } else if(S_ISDIR(st.st_mode)) {
1552 if (st.st_dev == st_kp.st_dev && st.st_ino == st_kp.st_ino)
1553 return NULL; /* drop scan kp/ directory */
1554 /* direntry is directory. buff is returned */
1555 return bb_xstrdup(fp);
1557 /* hmm, direntry is device! */
1561 /* from libbb but inlined for speed considerations */
1562 static inline llist_t *llist_add_to(llist_t *old_head, char *new_item)
1566 new_head = xmalloc(sizeof(llist_t));
1567 new_head->data = new_item;
1568 new_head->link = old_head;
1573 static void scan_dir_find_ch_files(const char *p)
1582 dirs = llist_add_to(NULL, bb_simplify_path(p));
1583 replace = strlen(dirs->data);
1584 /* emulate recursion */
1588 dir = opendir(dirs->data);
1590 fprintf(stderr, "Warning: opendir(%s): %m\n", dirs->data);
1591 dirlen = strlen(dirs->data);
1592 while ((de = readdir(dir)) != NULL) {
1595 if (de->d_name[0] == '.')
1597 found_dir = parse_chd(de->d_name, dirs->data, dirlen);
1599 d_add = llist_add_to(d_add, found_dir);
1611 static void show_usage(void) ATTRIBUTE ((noreturn));
1612 static void show_usage(void)
1614 bb_error_d("%s\n%s\n", bb_mkdep_terse_options, bb_mkdep_full_options);
1617 int main(int argc, char **argv)
1624 /* for bb_simplify_path, this program has no chdir() */
1625 /* libbb-like my xgetcwd() */
1626 unsigned path_max = 512;
1628 s = xmalloc (path_max);
1629 while (getcwd (s, path_max) == NULL) {
1631 bb_error_d("getcwd: %m");
1633 s = xmalloc(path_max *= 2);
1638 while ((i = getopt(argc, argv, "I:c:dk:w")) > 0) {
1641 s = bb_simplify_path(optarg);
1642 Iop = llist_add_to(Iop, s);
1645 s = bb_simplify_path(optarg);
1646 configs = llist_add_to(configs, s);
1649 dontgenerate_dep = 1;
1653 bb_error_d("Hmm, why multiple -k?");
1654 kp = bb_simplify_path(optarg);
1665 kp = bb_simplify_path(INCLUDE_CONFIG_PATH);
1666 /* globals initialize */
1667 kp_len = strlen(kp);
1668 if(stat(kp, &st_kp))
1669 bb_error_d("stat(%s): %m", kp);
1670 if(!S_ISDIR(st_kp.st_mode))
1671 bb_error_d("%s is not directory", kp);
1674 Iop = llist_add_to(Iop, bb_simplify_path(LOCAL_INCLUDE_PATH));
1675 if(configs == NULL) {
1676 s = bb_simplify_path(INCLUDE_CONFIG_KEYS_PATH);
1677 configs = llist_add_to(configs, s);
1680 pagesizem1 = getpagesize() - 1;
1681 for(i = 0; i < UCHAR_MAX; i++) {
1684 /* set unparsed chars to speed up the parser */
1685 else if(i != CHR && i != STR && i != POUND && i != REM)
1686 first_chars[i] = ANY;
1688 first_chars[i] = '-'; /* L_EOF */
1691 for(fl = configs; fl; fl = fl->link) {
1694 if(stat(fl->data, &st))
1695 bb_error_d("stat(%s): %m", fl->data);
1696 c_lex_config(fl->data, st.st_size);
1698 /* trick for fast comparing found files with configs */
1699 fl->data = xmalloc(sizeof(struct stat));
1700 memcpy(fl->data, &st, sizeof(struct stat));
1707 scan_dir_find_ch_files(*argv++);
1709 scan_dir_find_ch_files(".");
1715 /* partial and simplified libbb routine */
1716 static void bb_error_d(const char *s, ...)
1721 vfprintf(stderr, s, p);
1727 static char *bb_asprint(const char *format, ...)
1734 va_start(p, format);
1735 r = vasprintf(&out, format, p);
1738 out = xmalloc(BUFSIZ);
1739 va_start(p, format);
1740 r = vsprintf(out, format, p);
1745 bb_error_d("bb_asprint: %m");
1749 /* partial libbb routine as is */
1751 static char *bb_simplify_path(const char *path)
1753 char *s, *start, *p;
1756 start = bb_xstrdup(path);
1758 /* is not libbb, but this program has no chdir() */
1759 start = bb_asprint("%s/%s", pwd, path);
1765 if (*s == '/') { /* skip duplicate (or initial) slash */
1767 } else if (*s == '.') {
1768 if (s[1] == '/' || s[1] == 0) { /* remove extra '.' */
1770 } else if ((s[1] == '.') && (s[2] == '/' || s[2] == 0)) {
1773 while (*--p != '/'); /* omit previous dir */
1782 if ((p == start) || (*p != '/')) { /* not a trailing slash */
1783 ++p; /* so keep last character */